Nginx的location指令用于匹配请求URI,语法如下:
location [modifier] pattern {
...
}
无修饰符:前缀匹配(区分大小写)
location /images/ {
# 匹配以/images/开头的URI
}
=
:精确匹配
location = /logo.png {
# 只匹配/logo.png
}
~
:正则匹配(区分大小写)
location ~ \.php$ {
# 匹配以.php结尾的URI,区分大小写
}
~*
:正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png)$ {
# 匹配图片文件,不区分大小写
}
^~
:优先前缀匹配(匹配后不再检查正则)
location ^~ /static/ {
# 匹配以/static/开头的URI,优先于正则匹配
}
=
^~
~
或 ~*
(按配置文件中出现的顺序)rewrite指令用于修改请求URI,语法:
rewrite regex replacement [flag];
简单的重写:
rewrite ^/oldpath$ /newpath permanent;
带参数的重写:
rewrite ^/product/(\d+)$ /item.php?id=$1? last;
条件重写:
if ($host != 'www.example.com') {
rewrite ^/(.*)$ http://www.example.com/$1 permanent;
}
server {
listen 80;
server_name example.com;
# 精确匹配首页
location = / {
rewrite ^ /index.php last;
}
# 静态文件处理
location ^~ /static/ {
root /var/www/html;
expires 30d;
}
# PHP文件处理
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
# 旧URL重定向
location /old/ {
rewrite ^/old/(.*)$ /new/$1 permanent;
}
# 商品详情页重写
location /product {
rewrite ^/product/(\d+)$ /detail.php?id=$1 last;
}
# 404处理
location / {
try_files $uri $uri/ =404;
}
}
rewrite_log on;
开启重写日志(需要设置error_log级别为notice)return 200 "message";
测试匹配情况bash
curl -I http://example.com/old/path
$1, $2
等捕获组时注意正则表达式的括号通过合理配置location和rewrite规则,可以实现灵活的URL路由、重定向和伪静态等功能。