nginx 代理服务
location中的try_files
location /images/ {
root /opt/html/;
try_files $uri $uri/ /images/default.gif;
}
比如 请求 127.0.0.1/images/test.gif 会依次查找
文件/opt/html/images/test.gif
文件夹 /opt/html/images/test.gif/下的index文件
请求127.0.0.1/images/default.gif
其他注意事项
try-files 如果不写上 $uri/,当直接访问一个目录路径时,并不会去匹配目录下的索引页
即 访问127.0.0.1/images/ 不会去访问 127.0.0.1/images/index.html
在 nginx 中使用 proxy_pass 来配置反向代理。
server {
# 端口
listen 8090;
server_name localhost;
# 反向代理到 java后台
location /api/xljkzx/ {
proxy_pass http://127.0.0.1:9023/;
}
}
上面配置会让你访问 http://localhost:8090/api/xljkzx/auth 时访问到 http://127.0.0.1:9023/auth
Nginx之proxy_pass指令url反斜杠作用
在nginx中配置proxy_pass代理转发时,其后面的url中反斜杠/ 的匹配处理时常出现意想不到的问题发生,以下说明两种情况:
(1)如果在proxy_pass后面的url加/,表示绝对根路径;
(2)如果在proxy_pass后面的url没有/,表示相对路径,把匹配的路径部分也给代理走。
下面六种情况分别用 http://127.0.0.1/proxy/test.html 进行访问测试
第一种情况:
location /proxy/ {
proxy_pass http://127.0.0.1/;
}
最终会被代理到URL:http://127.0.0.1/test.html
第二种情况(相对于第一种,最后少一个 / ):
location /proxy/ {
proxy_pass http://127.0.0.1;
}
最终会被代理到URL:http://127.0.0.1/proxy/test.html
第三种情况:
location /proxy/ {
proxy_pass http://127.0.0.1/aaa/;
}
最终会被代理到URL:http://127.0.0.1/aaa/test.html
第四种情况(相对于第三种,最后少一个 / ):
location /proxy/ {
proxy_pass http://127.0.0.1/aaa;
}
最终会被代理到URL:http://127.0.0.1/aaatest.html
第五种情况(定义了一个正则表达式,那么在URl部分没有转换发生):
location ~ ^/proxy/ {
proxy_pass http://127.0.0.1/aaa;
}
最终会被代理到URL:http://127.0.0.1/proxy/test.html
最佳写法为:
location ~ ^/proxy/ {
proxy_pass http://127.0.0.1;
}
第六种情况(有rewrite规则改变URl,那也不会发生转换):
location /proxy/ {
rewrite /proxy/(.*)$ /index.php?page=$1 break; # break标记用于立即停止rewrite模块的所有指令
proxy_pass http://127.0.0.1/aaa;
}
最终会被代理到URL:http://127.0.0.1/index.php?page=test.html
最佳写法为:
location /proxy/ {
rewrite /proxy/(.*)$ /index.php?page=$1 break;
proxy_pass http://127.0.0.1;
}