Nginx提供了强大的重定向和URL重写功能,主要通过rewrite
指令和return
指令实现。以下是详细的使用方法:
# 301永久重定向
server {
listen 80;
server_name olddomain.com;
return 301 http://newdomain.com$request_uri;
}
# 302临时重定向
server {
listen 80;
server_name temp.example.com;
return 302 http://example.com/temporary;
}
# 重定向特定路径
location /oldpath {
rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
}
# 重写URL但不重定向(客户端URL不变)
location /products {
rewrite ^/products/(.*)$ /items/$1 last;
}
# 如果文件不存在则重写
location /images {
try_files $uri @rewrite;
}
location @rewrite {
rewrite ^/images/(.*)$ /static/images/$1 last;
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
location / {
try_files $uri $uri/ $uri.php?$args;
}
location ~ \.php$ {
# PHP处理配置
}
rewrite ^/search/(.*)$ /search.php?q=$1? last;
rewrite ^/user/([0-9]+)/profile$ /profile.php?id=$1 last;
if ($http_user_agent ~* (mobile|android|iphone)) {
rewrite ^(.*)$ /mobile$1 last;
}
rewrite ^/path/(.*)$ /newpath/$1?$args last;
rewrite_log on;
开启重写日志(需要设置error_log级别为notice)nginx -t
return
进行简单重定向,性能更好if
条件判断,可能影响性能通过合理使用这些重定向和重写技术,您可以实现URL规范化、路由美化、旧链接迁移等多种需求。