Location指令用于匹配请求URI,语法如下:
location [modifier] pattern {
# 配置指令
}
无修饰符 - 前缀匹配
location /images/ {
# 匹配以/images/开头的URI
}
=
- 精确匹配
location = /logo.png {
# 只匹配/logo.png
}
~
- 区分大小写的正则匹配
location ~ \.php$ {
# 匹配以.php结尾的URI,区分大小写
}
~*
- 不区分大小写的正则匹配
location ~* \.(jpg|jpeg|png|gif)$ {
# 匹配图片文件,不区分大小写
}
^~
- 优先前缀匹配(不检查正则)
location ^~ /static/ {
# 匹配以/static/开头的URI,不检查后续的正则location
}
=
^~
~
或 ~*
(按配置顺序)Rewrite指令用于重写URL,语法如下:
rewrite regex replacement [flag];
简单重写:
rewrite ^/oldpath$ /newpath permanent;
捕获组使用:
rewrite ^/user/(.*)$ /profile?username=$1 last;
文件不存在时重写:
if (!-f $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}
server {
listen 80;
server_name example.com;
# 静态文件处理
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}
# PHP处理
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 重写规则 - 美化URL
location / {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^/(.*)$ /index.php?q=$1 last;
}
# 特定路径重定向
location = /old-page {
rewrite ^ /new-page permanent;
}
}
nginx -s reload
rewrite_log on;
可以开启重写日志便于调试希望这些配置示例能帮助你更好地理解和使用Nginx的location和rewrite规则。