如何使用Nginx实现带子域名与路径的批量URL重定向
Hey there! Let's get those Nginx redirects set up properly for your old-to-new URL mappings. I'll walk you through two solid approaches depending on how many rules you end up with:
This method uses precise location = directives, which are super efficient because Nginx stops processing further rules once a match is found. Perfect for your given examples.
First, configure the server block for your old subdomain (make sure to add your SSL config if using HTTPS):
# Redirect HTTP traffic to HTTPS first (always a good practice) server { listen 80; listen [::]:80; server_name subold.domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name subold.domain.com; # Add your SSL certificate/key config here # ssl_certificate /path/to/your/cert.pem; # ssl_certificate_key /path/to/your/key.pem; # Exact match redirects for each old path location = /old-path-0 { return 301 https://subnew.domain.com/new-path; } location = /old-path-1 { return 301 https://subnew.domain.com/new-path-alpha; } location = /old-path-2 { return 301 https://subnew.domain.com/new-path-gamma; } location = /old-path-3 { return 301 https://subnew.domain.com/new-path-2; } # Optional: Catch-all redirect for any other unmatched old paths location / { return 301 https://subnew.domain.com$request_uri; } }
If you end up with dozens or hundreds of redirect rules, using an Nginx map keeps your config clean and easy to maintain. Define the mappings once in the http block, then reference them in your server block:
http { # ... your existing global configs ... # Define the old-to-new path mappings here map $request_uri $new_target_path { /old-path-0 /new-path; /old-path-1 /new-path-alpha; /old-path-2 /new-path-gamma; /old-path-3 /new-path-2; # Add more mappings as needed, one per line } server { listen 80; listen [::]:80; server_name subold.domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name subold.domain.com; # SSL config here # ssl_certificate /path/to/your/cert.pem; # ssl_certificate_key /path/to/your/key.pem; # Redirect using the map value if it exists if ($new_target_path) { return 301 https://subnew.domain.com$new_target_path; } # Catch-all for remaining paths location / { return 301 https://subnew.domain.com$request_uri; } } }
Quick Notes:
- Use
301for permanent redirects (best for SEO, tells browsers/search engines to update their bookmarks/indexes). Use302only if the redirect is temporary. - Always test your config with
nginx -tbefore reloading Nginx withsystemctl reload nginx(or your distro's equivalent command).
内容的提问来源于stack exchange,提问作者Awol

