頁(yè)面nginx配置
1,前端頁(yè)面放在域名根目錄,比如,http://www.xuecheng.com/ ,對(duì)應(yīng)的nginx配置:
#門(mén)戶 location / { alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/; index index.html; }
頁(yè)面目錄:
接口nginx配置
2,前端請(qǐng)求接口路徑,在域名后面加一個(gè)目錄
url : "http://www.xuecheng.com/api/auth/oauth/token",//發(fā)送請(qǐng)求的地址
function login(){ var uname = $("#username").val(); var pwd = $("#password").val(); $.ajax({ url : "http://www.xuecheng.com/api/auth/oauth/token",//發(fā)送請(qǐng)求的地址 type: "post", dataType: "json", data : "username="+uname+"&password="+pwd+"&grant_type=password", beforeSend:function (request) { // 如果后臺(tái)沒(méi)有跨域處理,這個(gè)自定義 request.setRequestHeader("Authorization","Basic RG9jV2ViQXBwOjEyMzQ1Ng=="); // 禁用按鈕,防止重復(fù)提交 $("#submit").attr({ disabled: "disabled" }); }, error : function() { alert("error occured!!!");//請(qǐng)求失敗時(shí)彈出的信息 }, success : function(data) {//返回的信息展示出來(lái) alert(JSON.stringify(data)) } }); };
nginx 對(duì)api接口配置
location /api/ { add_header 'Access-Control-Allow-Origin' $http_origin; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } proxy_pass http://apiserver/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 5; }
其中的
$http_origin
$http_origin并不是nginx的內(nèi)置參數(shù),nginx支持取自定義的參數(shù)值,$http_XXX這個(gè)格式是nginx取請(qǐng)求中header的XXX的值的。這里取的是origin,而一般跨域請(qǐng)求都會(huì)將請(qǐng)求的來(lái)源放在origin中(瀏覽器會(huì)往跨域請(qǐng)求的header上面加origin這個(gè)header)。
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-410307.html
?
這樣配置的話,前端頁(yè)面在域名下:www.xuecheng.com,而訪問(wèn)的接口則是www.xuecheng.com/api/xxx ,這樣就不存在跨域問(wèn)題了,
其實(shí)nginx不配置??Access-Control-Allow-Origin也沒(méi)事,因?yàn)榍昂蠖嗽谝粋€(gè)域下了。
注意事項(xiàng)
如果你前后端訪問(wèn)存在跨域問(wèn)題,而且你需要使用cookie,后端要想獲取到前端攜帶過(guò)來(lái)的cookie,前后端都要做配置:
前端:
var xhr = new XMLHttpRequest() xhr.withCredentials = true xhr.open('GET', 'http://localhost:8888/', true) xhr.send(null)
后端:
Access-Control-Allow-Origin: http://www.abc.com(這里必須域名不能是*) Access-Control-Allow-Credentials: true
完整nginx配置
#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; #微服務(wù)網(wǎng)關(guān) upstream apiserver{ server 127.0.0.1:50101; } server { listen 80; server_name www.xuecheng.com; ssi on; ssi_silent_errors on; #charset koi8-r; #access_log logs/host.access.log main; #門(mén)戶 location / { alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/; index index.html; } #location / { # root /neworiental/www/jiaofu; # index index.html; # try_files $uri /index.html; #} # proxy_pass末尾有/,請(qǐng)求地址:http://localhost/api/test,轉(zhuǎn)發(fā)地址:http://127.0.0.1:8000/test location /api/ { add_header 'Access-Control-Allow-Origin' $http_origin; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } proxy_pass http://apiserver/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 5; } location ^~ /openapi/auth/ { proxy_pass http://apiserver/auth/; } #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; # } #} }
參考:
正確的Nginx跨域配置:https://blog.csdn.net/envon123/article/details/83270277
跨域資源共享(CORS)安全性:https://blog.csdn.net/weixin_43964148/article/details/109352413文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-410307.html
?
到了這里,關(guān)于巧用Nginx配置解決跨域問(wèn)題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!