centOS7云服务器nginx代理前后端分离项目配置 最近用Nginx做了一个项目代理,下面简单记录一下知识点以备不时之需。 1.因为此云服务器安全性较高,需要连接VPN用到跳板机操作。因为连接了专用网络,操作时就要断掉本机外网,所以搭建之前尽量做好准备工作。 2.实验证明,在云服务器上用yum安装Nginx比编译安装要方便一些。(因为编译安装可能少插件,也要考虑版本问题,卸载容易有残留) centos7中可能不包含Nginx源,所以我们手动添加一下: rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm 通过yum search nginx看看是否已经添加源成功。如果成功则执行下列命令安装Nginx: yum install -y nginx 启动Nginx: systemctl start nginx.service (如果没有环境变量可能要用到nginx -c /etc/nginx/nginx.conf命令启动) 查看Nginx状态: systemctl status nginx.service 系统默认会安装到/etc/Nginx目录下,有一点要注意的是,我安装的Nginx下有两个nginx.conf文件,两个位置分别在/etc/nginx/nginx.conf 和/etc/nginx/conf/nginx.conf 注意看具体哪个配置文件生效,大部分是第一个。 3.因为此时本机处于断网状态,所以代码需要wget下来。(此处忽略php7.4和composer的安装教程) 4.记好代码位置后,进行nginx配置: 在http{}层级下编辑server{}格式的代理,具体如下: user nginx nginx; worker_processes auto;
error_log /etc/nginx/logs/error.log notice; pid /etc/nginx/logs/nginx.pid;
events { worker_connections 1024; }
http {
include /etc/nginx/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"';
gzip on;
gzip_static on;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javas cript;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
add_header X-Frame-Options SAMEORIGIN;
server {
listen 443 ssl;
listen 80;
server_name www.xxx.cn;
root /code/ctwaf;
location / {
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate /etc/nginx/conf/www.xxx.cn_bundle.crt;
ssl_certificate_key /etc/nginx/conf/www.xxx.cn_RSA.key;
ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
ssl_prefer_server_ciphers on;
location /xxxx/ {
proxy_pass http://127.0.0.1:8080/xxxx/;
}
}
server {
listen 8080;
server_name _;
#server_name www.xxx.cn;
root /code/ctwaf_server/public;
location / {
index index.php;
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?s=$1 last;
}
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html{
root html;
}
}
access_log /etc/nginx/logs/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
server_tokens off;
}
其中要注意的点: nginx的操作用户,可改为nginx或root(自己斟酌); 错误日志路径(方便后期调试查看); Pid路径; 如果有https 协议,在ssl_certificate和ssl_certificate_key后分别写上公钥和私钥的路径; 反向代理proxy_pass指向本机8000,代表80的/xxxx/的接口指向8080的/xxxx/; PHP项目需要启动php-fpm,默认占用9000端口 这样一个前后端分离的项目基本配置完成,如果修改nginx配置,记得执行nginx -s reload生效。