一.为什么使用Nginx
首先,我们知道,为了系统的高可用,我们的系统一般会部署多个实例
但是,这样是存在问题的,我们应该要对用户屏蔽掉这一信息。因为客户不可能被我们安排在特定时间去访问特定的服务器。这明显是行不通的,首先,用户无法记住这么多的服务器地址,其次,系统管理者难以管理运营
二.反向代理
反向代理就是使用一台代理服务器对底层的应用服务器进行代理,客户只需要访问代理服务器就可以了,代理服务器会将请求转发给底层服务器,但是在客户眼里服务器就是只用一台
三.Nginx的配置与使用
3.1下载nginx
下载地址:nginx: download
可以根据自己的需求下载不要下错,下载后解压后,文件结构:
然后打开conf配置文件里面的nginx.conf
然后再http里面添加一下代码:
server {
listen 9001;
server_name localhost;location ~ /acl/ {
proxy_pass http://localhost:8201;
}location ~ /sys/ {
proxy_pass http://localhost:8202;
}
location ~ /product/ {
proxy_pass http://localhost:8203;
}
}
可以看到建立的端口号为9001,这个可以根据你要访问的端口号进行修改,然后server_name 这是我们的本机名,location ~/acl/这个你可以理解为正则表达式,当你的请求包含acl那么访问的端口号就是8201,后面的两个跟这个一样
完整配置文件代码:
#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;server {listen 81;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}# 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;#}}# 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;# }#}# HTTPS server##server {# listen 443 ssl;# server_name localhost;# ssl_certificate cert.pem;# ssl_certificate_key cert.key;# ssl_session_cache shared:SSL:1m;# ssl_session_timeout 5m;# ssl_ciphers HIGH:!aNULL:!MD5;# ssl_prefer_server_ciphers on;# location / {# root html;# index index.html index.htm;# }#}server {listen 9001;server_name localhost;location ~ /acl/ { proxy_pass http://localhost:8201;} location ~ /sys/ { proxy_pass http://localhost:8202;}location ~ /product/ { proxy_pass http://localhost:8203;}}}
四.启动Nginx
我们可以直接双击nginx.exe运行,也可以使用命令运行。
直接在我们的nginx文件夹输入cmd后回车输入命令:
//启动
nginx.exe
如果你要关闭的话直接退出cmd是没用的,我们可以使用命令关闭,或者你也可以直接关机当然我是不推荐这样做的
//关闭
nginx.exe -s stop
这样就算启动了
五.缺点
这样做虽然可以访问不同的端口号了,但是有一个缺点就是你没加一个服务端口,就要在配置文件进行配置,有时候还可能忘记加导致访问请求错误