本文共 3323 字,大约阅读时间需要 11 分钟。
Nginx中常用的正则表达式符号及其含义:
location = / { ... }
:只匹配根路径location / { ... }
:匹配所有路径location ~ / { ... }
:结合正则表达式进行匹配location = / { ... }
:严格匹配根路径^~ /
:表示普通字符匹配~ /
:与^~类似但区分大小写~* /
:与~类似但不区分大小写!~ /
:与~类似但匹配非指定路径!~* /
:与~*类似但匹配非指定路径优先级从高到低依次为:
location = /
)location /
)^~ /
)~ /
或 ~* /
)location = / { proxy_pass http://tomcat_server/; }
:只匹配根路径,所有其他路径不匹配location / { proxy_pass http://tomcat_server/; }
:匹配所有路径location ~ /images/ { proxy_pass http://backend/; }
:匹配以/images/
开头的路径location /static/ { root /webroot/static/; } location ~* \.(html|gif|jpg|jpeg|png|css|js|ico)$ { root /webroot/res/; }
:分别处理静态文件和其他文件类型$host
、$request_uri
等last
、break
、redirect
、permanent
rewrite regex replacement [flag];
server { listen 80; server_name www.zhangsan.com; charset utf-8; access_log /var/log/nginx/www.zhangsan.com.access.log; location / { if ($host = 'www.zhangsan.com') { rewrite ^/(.*)$ http://www.lisi.com/$1 permanent; } root html; index index.html index.htm; }}
server { listen 80; server_name www.zhangsan.com; charset utf-8; access_log /var/log/nginx/bbs.zhangsan.com.access.log; if ($remote_addr = "192.168.172.10") { set $rewrite false; } if ($rewrite = true) { rewrite (.+) /weihu.html; } location /weihu.html { root /var/www/html; } location / { root html; index index.html index.htm; }}
server { listen 80; server_name bbs.zhangsan.com; charset utf-8; access_log /var/log/nginx/bbs.zhangsan.com.access.log; location /post { rewrite (.+) http://www.zhangsan.com/bbs/$1 permanent; } location / { root html; index index.html index.htm; }}
server { listen 80; server_name www.zhangsan.com; charset utf-8; access_log /var/log/nginx/www.zhangsan.com.access.log; if ($request_uri ~ ^/100-(100|200)-(\d+).html$) { rewrite (.+) http://www.zhangsan.com permanent; } location / { root html; index index.html index.htm; }}
server { listen 80; server_name www.zhangsan.com; charset utf-8; access_log /var/log/nginx/www.zhangsan.com.access.log; location ~* /upload/.*\.php$ { rewrite (.+) http://www.zhangsan.com permanent; } location / { root html; index index.html index.htm; }}
location ^~ /static/ { root /webroot/static/;}location ~* \.(html|gif|jpg|jpeg|png|css|js|ico)$ { root /webroot/res/;}
location / { proxy_pass http://tomcat_server;}
优先级从高到低依次为:
location = /
location /
location ^~ /
location ~ /
或 location ~* /
location
正则匹配通过合理配置location
和rewrite
,可以实现对网站请求的精细化控制和重写,提升Nginx的性能和功能。
转载地址:http://xzag.baihongyu.com/