新項目采用前后端分離的方式開發,前后端代碼打算分開部署(同機器且同域名),但打算支持后端依然可訪問靜態資源(nginx配置僅一份)。
搜索nginx配置大部分都通過url前綴進行轉發來做前后端分離,不適用目前項目。
說明
前端框架:vue
后端框架:thinkphp6
前端部署目錄:/www/project_static
后端部署目錄:/www/project
nginx配置方式
`api`及`static`轉發到php
server { listen 80; server_name test.aichenk.com; index index.html index.htm index.php; set $static_root '/www/project_static'; set $php_root '/www/project/public'; root $static_root; location ~ \.php$ { root $php_root; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_buffer_size 128k; fastcgi_buffers 32 32k; } location / { try_files $uri $uri/ /index.html; } location ^~ /api/ { root $php_root; if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; break; } } location ^~ /static/ { root $php_root; access_log off; } # 禁用緩存 location = /index.html { add_header Cache-Control no-cache; add_header Pragma no-cache; add_header Expires 0; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; access_log off; } }
另外可通過反向代理方式,若第一次判斷文件不存在,則發送到另一個服務中,服務中僅關注后端配置。