Nginx搭建、代理服务
一. 环境搭建
- 下载nginx
链接:https://pan.baidu.com/s/1b6PttHknU6bnxObJIYajyg
提取码:ce8y
也可以在线安装(我是直接离线安装的)
wget http://nginx.org/download/nginx-1.14.2.tar.gz
- 解压
下载完后,通过ftp软件把我们刚刚下载的包传到我们的服务器上去
接着我们对该压缩文件进行解压,进入home文件夹(我是把nginx包放在home)
tar -zxvf nginx-1.13.0.tar.gz
解压完之后会在出现个nginx文件夹源代码 nginx-1.13.0
3. 编译环境
在编译之前,我们还得要装一些依赖
# nginx环境所需依赖
yum -y install pcre*
# nginx开启https的依赖
yum -y install openssl*
依赖解决完之后,我们来开始安装:
进入刚才解压的文件夹nginx-1.13.0
中
# 1.执行文件,检查配置文件是否生效
./configure
# 2.编译源代码
make
# 3.安装
make install
到这里,安装应该算基本完事。可以去/usr/local/
下面看看是不是多了个nginx
的文件夹
这里就是我们刚刚安装在系统里生成的nginx服务的文件夹了
4. 运行nginx
进入/usr/local/nginx/
,直接运行
# 因为nginx默认配置的是80端口,所以在运行前,先确认下服务器的80端口有没有被占用
./nginx
运行完之后,不出意外访问你的服务器ip就可以访问了
二.用一个nginx配置不同域名访问不同服务
- 场景描述:
在当前服务器下,有两个域名 www.test1.com 和www.test2.com都对这个服务器ip进行绑定。在服务器中搭建服务A、B,在不过代理访问的情况下,我所了解的是不能用两个域名直接就可以访问对应的服务。比如我访问www.test1.com就是A服务,www.test2.com就是B服务。
- 解决方案:
为了解决上述的问题,这时候就得要代理访问了
打开/usr/local/nginx/conf/nginx.conf
配置文件
贴上对应的配置:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
#test1服务
server {
listen 80;
server_name www.test1.com test1.com;
location / {
proxy_pass http://ip:9000/A/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
#test2服务
server {
listen 80;
server_name www.test2.com test2.com;
location / {
proxy_pass http://ip:9002/B/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
通过两个server
的配置,可以对两个域名进行代理。
- listen 代理对外暴露的端口(默认80)
- server_name 你的域名访问的名称(所以在这里的www.test1.com能访问到我们要代理的地方)
- proxy_pass 我们要代理的url
保存好配置文件后,在nginx/sbin/
重新运行下nginx./nginx -s reload
,这样我们的域名映射服务的需求就算完成了。