location
location 匹配规则
= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)
~ 开头表示区分大小写的正则匹配
~* 开头表示不区分大小写的正则匹配
!~ 和 !~*分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。
root
拼接
请求URL: 127.0.0.1/home/ 实际访问路径: /home/home/dist/下内容
location /home/ {
root /home/dist;
}
alias
替换
请求URL: 127.0.0.1/home/ 实际访问路径: /home/dist/下类容
location /home/ {
alias /home/dist;
}
proxy_pass
请求URL: 127.0.0.1/api/v2 实际访问路径: http://192.168.1.50/
location /api/v2/ {
proxy_pass http://192.168.1.50/;
}
请求URL: 127.0.0.1/api/v2 实际访问路径: http://192.168.1.50/api/v2
location /api/v2/ {
proxy_pass http://192.168.1.50;
}
请求URL: 127.0.0.1/api/v2 实际访问路径: http://192.168.1.50/dddd/api/v2/
location /api/v2/ {
proxy_pass http://192.168.1.50/dddd/api/v2/;
}
代理 设置跨域
location /api/v2 {
proxy_pass http://www.baidu.com;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
例子
server {
listen [::]:8000; ## 匹配的ip和端口 可以只写端口 此处是匹配所有ip地址的8000端口
# server_name web; ## 匹配的域名 如果listen 设置了ip 则不需要设置
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
# gzip config 压缩相关配置
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
# 路径匹配规则
location / {
# url/ 匹配至/root/dist/index.html 此静态页面
root /root/dist;
index index.html index.htm;
}
location /api/v2 {
proxy_pass http://preview.pro.loacg.com;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
location /api/ne {
proxy_pass http://10.42.40.20:5000;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
#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 /usr/share/nginx/html;
}
}