Nginx域名后添加语言代码及多场景URL重定向配置咨询
Nginx Redirect Solution for Language Prefix Handling
Hey there! Let's work through those redirect scenarios you need sorted out. You already have the root path redirect covered, so let's expand that config to handle all three cases cleanly.
Here's the complete Nginx config snippet that addresses every scenario:
# Redirect root domain to /en-us/ (your existing rule) location = / { rewrite ^ /en-us/ redirect; } # Redirect non-language-prefixed paths to /en-us/[original-path] # Excludes paths starting with /en-us/ or other language codes like /en-in/ location ~ ^/(?!en-us/|en-in/)(.*) { rewrite ^/(.*)$ /en-us/$1 redirect; }
Let's break down what each part does to match your requirements:
- Scenario 1: http://example.com/contact → http://example.com/en-us/contact
The second rule uses a negative lookahead regex ((?!en-us/|en-in/)) to catch any path that doesn't start with a recognized language prefix./contactfalls into this category, so it gets rewritten to/en-us/contactand redirected. - Scenario 2: http://example.com/en-us/ stays as-is
Since/en-us/is explicitly excluded in the negative lookahead, this path won't trigger the second rule. Your root rule only matches exactly/, so/en-us/(and subpaths like/en-us/contact) are left untouched—no duplicate prefix added. - Scenario 3: http://example.com/en-in/ remains unchanged
Just like/en-us/,/en-in/is added to the exclusion list in the regex. Any path starting with/en-in/will bypass the redirect rule and keep its original path.
Quick Notes:
- If you add more language codes later (like
/fr-fr/or/es-es/), just append them to the negative lookahead separated by a|, e.g.,(?!en-us/|en-in/|fr-fr/). - Use
redirectfor temporary 302 redirects. If this is a permanent change, swap it forpermanent(301) — but be cautious, as 301s are heavily cached by browsers.
内容的提问来源于stack exchange,提问作者Karthi Skb
相关产品推荐
相关产品推荐

