nginx第一篇:各种坑
1、在nginx配置跨域
关于跨域的讲解,阮一峰写的很好https://www.ruanyifeng.com/blog/2016/04/cors.html
在浏览器页面访问,跨域时,在控制台会有提示,如
Access to XMLHttpRequest at 'https://backend_domain/base/v1/upload' from origin 'https://fontend_domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
查到方案如下
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, DELETE, PUT, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
但实际上,如果是微服务的话,比如/s1/开头的接口转发至s1服务,/s2/开头的接口转发至s2服务,这种情况下,配置location / {}不会处理任何接口。
查看官方文档https://nginx.org/en/docs/http/ngx_http_headers_module.html知,add_header的作用域有http、server、location,所以我们把add_header放到location外面、server里面就好了,如
server {
listen 80;
server_name backend.com;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, DELETE, PUT, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
access_log /usr/local/openresty/nginx/logs/access.log main;
location /user {
proxy_pass http://user_service;
}
location /base {
proxy_pass http://base_service;
}
}
注意,nginx和业务后台不能都设置跨域,否则就会出现下面的效果:

2、在nginx配置80转发443
在网上查到很多文章,提供方案如下
server {
listen 80;
server_name www.域名.com;
rewrite ^(.*)$ https://${server_name}$1 permanent;
}
但实际上,这样做会导致所有请求都变为GET请求,MLGB的
正确的方案:
①、使用return 307。当发送重定向请求时,307状态码可以确保请求方法和消息体不会发生变化。
server {
listen 80;
if ($scheme != https) {
return 307 https://127.0.0.1$request_uri;
}
}
②、把对80端口的监听和对443端口的监听写到同一个server块中,如
server {
listen 80;
listen 443 ssl;
http2 on;
server_name backend.com;
# ssl证书、协议配置略
access_log /usr/local/openresty/nginx/logs/access.log main;
location /user {
proxy_pass http://user_service;
}
location /base {
proxy_pass http://base_service;
}
}
浙公网安备 33010602011771号