Nginx的map
指令可以创建变量映射,结合rewrite
或return
指令可以实现灵活的页面跳转功能。以下是几种实现方式:
http {
# 定义映射关系
map $uri $new_url {
default "";
/old-page /new-page;
/about-us /about;
/products.html /catalog;
}
server {
listen 80;
server_name example.com;
# 如果匹配到映射关系,则进行301重定向
if ($new_url) {
return 301 $new_url;
}
# 其他配置...
}
}
http {
map $uri $redirect_flag {
default 0;
/old-page 1;
/about-us 1;
/products.html 1;
}
server {
listen 80;
server_name example.com;
# 如果匹配到需要跳转的URL
if ($redirect_flag) {
rewrite ^ $scheme://$host/new-destination permanent;
}
# 其他配置...
}
}
map $uri $new_url {
default "";
~^/old-blog/(.*) /blog/$1;
~^/products/([0-9]+) /items/$1;
}
map $request_uri $redirect_uri {
default "";
# 旧URL路径到新URL路径的映射
/old-path1 /new-path1;
/old-path2 /new-path2;
/category/old-cat /shop/new-cat;
/products/old-product.html /items/new-product;
# 带参数的重定向
/search?q=nginx /docs/nginx;
}
server {
if ($redirect_uri) {
return 301 $redirect_uri;
}
}
map $host $new_host {
default "";
old.example.com new.example.com;
}
server {
listen 80;
server_name old.example.com;
if ($new_host) {
return 301 $scheme://$new_host$request_uri;
}
}
性能考虑:map指令在Nginx启动时加载到内存中,查询速度很快,适合大量规则的场景
维护性:将复杂的映射规则放在单独的配置文件中,通过include引入
map $uri $new_url {
include /etc/nginx/redirects.map;
}
测试工具:使用nginx -t
测试配置语法是否正确
缓存控制:对于永久重定向(301),浏览器会缓存结果,开发时可暂时使用302重定向
日志记录:添加日志记录重定向情况,便于调试
log_format redirect_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status "$http_referer" '
'"$http_user_agent" "$new_url"';
access_log /var/log/nginx/redirect.log redirect_log;
通过合理使用map指令,可以实现高效、灵活且易于维护的页面跳转规则,特别适合大规模URL重定向场景。