/

NGINX 前后端分离配置

前后端分离的开发已是主流,本文主要是记录前后端分离项目的 NGINX 配置。

  • 前端 Vue web 入口 host.test
  • 后端 PHP Yii service 入口 host.test/api
server {
listen 80;
server_name host.test;
root /data/project/web/dist/;
index index.html index.php;

location ^~/api {
root /data/project/service/web/;

access_log logs/service-access.log;
error_log logs/service-error.log;

fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
fastcgi_param SCRIPT_FILENAME /data/project/service/web/index.php;
fastcgi_param SCRIPT_NAME /api/index.php;
}

location /index.html {
add_header Cache-Control "no-cache, no-store";
}

location ^~ / {
alias /data/project/web/dist/;
access_log logs/web-access.log;
error_log logs/web-error.log;
}
}

负载均衡场景

  • 前端 Vue web 入口 host.test
  • 后端 PHP Yii service 入口 host.test/api 代理到 api.host.test

WEB

server {
listen 80;
server_name host.test;
root /data/project/web/dist/;

access_log logs/web-access.log;
error_log logs/web-error.log;

location /index.html {
add_header Cache-Control "no-cache, no-store";
}

location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.html;
}

location ^~/api/ {
proxy_set_header Host api.host.test;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://api.host.test/;
}
}

SERVICE

server {
listen 80;
server_name api.host.test;
root /data/project/service/web/;

location / {
access_log logs/service-access.log;
error_log logs/service-error.log;

index index.php index.html;
try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
fastcgi_pass 127.0.0.1:10071;

fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SERVER_NAME $http_host;
fastcgi_ignore_client_abort on;
}
}

NGINX 配置转发

location 进行的是模糊匹配。

  • 当结尾没有 / 时,location /abc/def 可以匹配 /abc/defghi 请求,也可以匹配 /abc/def/ghi 等。
  • 当结尾有 / 时,location /abc/def/ 不能匹配 /abc/defghi 请求,只能匹配 /abc/def/anything 这样的请求。

下面四种情况分别用 http://192.168.1.4/proxy/test.html 进行访问:

第一种:

location /proxy/ {
proxy_pass http://127.0.0.1:81/;
}

会被代理到 http://127.0.0.1:81/test.html

第二种(相对于第一种,最后少一个 /):

location /proxy/ {
proxy_pass http://127.0.0.1:81;
}

会被代理到 http://127.0.0.1:81/proxy/test.html

第三种:

location /proxy/ {
proxy_pass http://127.0.0.1:81/ftlynx/;
}

会被代理到 http://127.0.0.1:81/ftlynx/test.html

第四种(相对于第三种,最后少一个 /):

location  /proxy/ {
proxy_pass http://127.0.0.1:81/ftlynx;
}

会被代理到 http://127.0.0.1:81/ftlynxtest.html

– EOF –