1.rewrite的作用和用法
nginx可以在nginx配置文件中使用rewrite语法改写请求的url路径。 rewrite语法,rewrite 可以基于正则匹配,replacement表示替换后的url rewrite perl正则表达式 replacement [flag] flag:有4个值
flag | 含义 |
---|
break | 中止当前块中的rewrite语句和return语句 | last | 中止当前块中的rewrite语句和return语句,尝试匹配下一个location块 | redirect | 302重定向 | permanent | 301 重定向,和redirect的区别是,http状态码的区别,表示请求的资源被永久转移了 |
rewrite 语句可以存在server,location,if中
2.rewrite 语句的示例
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
upstream s1{
server 192.168.72.1:8081;
}
upstream s2{
server 192.168.72.1:8080;
}
server {
listen 80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
#rewrite ^(.*)/1.html /app/2.html last;
#rewrite ^(.*)/2.html /app/test.html break;
rewrite ^/app/test.html /a break;
location /app {
#rewrite ^/(.*)?(.*)$ https://www.baidu.com redirect;
proxy_pass http://s1;
proxy_set_header Accept-Encoding "";
sub_filter 'springMVC' 'SPRINGBOOT';
sub_filter_types *;
sub_filter_once off;
}
location /a{
rewrite ^/a /app/hello2 break;
}
location / {
proxy_pass http://s1;
}
}
#include /etc/nginx/conf.d/*.conf;
}
rewrite 的replacement也支持引用分组 如
rewrite ^(.*) http://my.host/$1 last
更多详细配置可查看官方文档 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
|