nginx配置文件以下:前端
server { listen 80; server_name your.domain.name; location / { # 把跟路徑下的請求轉發給前端工具鏈(如gulp)打開的開發服務器 # 若是是產品環境,則使用root等指令配置爲靜態文件服務器 proxy_pass http://localhost:5000/; } location /api/ { # 把 /api 路徑下的請求轉發給真正的後端服務器 proxy_pass http://localhost:8080/service/; # 把host頭傳過去,後端服務程序將收到your.domain.name, 不然收到的是localhost:8080 proxy_set_header Host $http_host; # 把cookie中的path部分從/api替換成/service proxy_cookie_path /api /service; # 把cookie的path部分從localhost:8080替換成your.domain.name proxy_cookie_domain localhost:8080 your.domain.name } }
配置完成後重啓nginx服務:nginx
nginx -s reload
flying get√ 老是要拼了命繼續努力gulp
目前不少網站都是用先後端徹底分離的模式實現,即:後端經過API提供數據,前端使用API獲取數據並渲染。不過這樣作會存在API跨域的問題,這裏介紹一種經過Nginx配置解決跨域問題的方法。後端
Nginx總體配置以下:api
upstream service { server 127.0.0.1:8080; } map $http_origin $cors_header { default ""; "~^https?://localhost(:[0-9]+)?$" "$http_origin"; } server { listen 80; server_name 127.0.0.1; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location = /favicon.ico { deny all; error_log off; access_log off; log_not_found off; } location /api/ { if ($request_method = 'OPTIONS') { add_header 'Content-Length' 0 always; add_header 'Content-Type' 'text/plain charset=UTF-8' always; add_header 'Access-Control-Allow-Origin' '$cors_header' always; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always; return 200; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '$cors_header' always; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '$cors_header' always; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; } uwsgi_pass service; include uwsgi_params; } }
API路徑配置中的 "X-AUTH-USER, X-AUTH-TOKEN",是API中傳遞的自定義HEADER,須要在 "Access-Control-Allow-Headers"中指明。 其中,"map $http_origin $cors_header"將須要跨域的域名或者IP解析出來,方便後面的配置處理。跨域