为记录遇到的Nginx问题:

1、nginx转发到其他地址,因为server层默认配置的proxy_set_header Host $host;
需要在location层配置proxy_set_header Host $proxy_host;


location /xxx/ {
proxy_pass http://www.baidu.com/;
proxy_set_header Host $proxy_host;
}

2、nginx图片跨域问题

##在location配置

location /xxx/ {
proxy_pass http://xxx:80/;

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, 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;
}
}

*3、图片跨域问题解决带cookie,主要1、add_header Access-Control-Allow-Origin不能用
主要2、add_header Access-Control-Allow-Credentials true;**

location /file/ {
proxy_pass http://xxxx:80/;
#指定允许跨域的方法,*代表所有
add_header Access-Control-Allow-Methods *;
#预检命令的缓存,如果不缓存每次会发送两次请求
add_header Access-Control-Max-Age 3600;
#带cookie请求需要加上这个字段,并设置为true
add_header Access-Control-Allow-Credentials true;
#表示允许这个域跨域调用(客户端发送请求的域名和端口)
#$http_origin动态获取请求客户端请求的域 不用*的原因是带cookie的请求不支持*号
add_header Access-Control-Allow-Origin $http_origin;
#表示请求头的字段 动态获取
add_header Access-Control-Allow-Headers
$http_access_control_request_headers;
#OPTIONS预检命令,预检命令通过时才发送请求
#检查请求的类型是不是预检命令
if ($request_method = OPTIONS){
return 204;
}
}

###一般使用如下即可

location / {
root /upload/;
index index.html index.htm;
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,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}

备注:
若配置了带cookie,在添加add_header Access-Control-Allow-Origin *; 会报错

has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' 
when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the 
withCredentials attribute

**4、前端默认跳转到index.html,需要在应用所在的nginx修改,
不能在(暂时没发现怎么处理)nginx转发处理即:不能在以下修改***

location /yytour/ {
proxy_pass http://xxxxxx:80/;
}

location ^~ /yytour/admin/ {
root /usr/share/nginx/html;
try_files $uri $uri/ /yytour/admin/index.html;
}

5、nginx转发配置缓存

location /xxxxx/ {
proxy_pass http://xxxxxx:80/;
if ($request_filename ~* ^.*?\.(htm|html)$){
add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";
expires -1;
}
if ($request_filename ~* ^.*?\.(gif|jpg|jpeg|png|bmp|swf)$){
expires 30d;
}
if ($request_filename ~* ^.*?\.(js|css)$){
expires 12h;
}
}

**6、alias和root的区别

location /img/ {
alias /var/www/image/;
}
#若按照上述配置,访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件

location /img/ {
root /var/www/image;
}
#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。]
alias是一个目录别名的定义,root则是最上层目录的定义。

alias后面必须要用“/”结束