Redirect domain to default language NGINX

寵の児 提交于 2020-04-17 22:56:15

问题


Been struggling for so long to 301 redirect site.com to site.com/en and site.com/my-page to site.com/en/my-page

I manage to make the first redirect work, but not the second! also is it possible to use only one rule for both? So what is wrong with my second rule?

rewrite "^/(?![a-z]{2}|[a-z]{2}-[a-z]{2})$" /en redirect;
rewrite "^/(?![a-z]{2}|[a-z]{2}-[a-z]{2})/(.*)$" /en/$2 redirect;

Thanks a lot in advance.


回答1:


You don't have 2 capture groups in the the second regexp, only one. The first pair of parenthesis there is a negative lookahead, which doesn't create a capture group. That's why you cannot use $2 in redirect.

Updated

This redirect should replace both your rules:

rewrite "^((?!/([a-z]{2}|[a-z]{2}-[a-z]{2})(/|$)).*)$" /en$1 last;



回答2:


I think you can approach it from the other angle, by defining relevant locations, e.g.:

location / {
    return 301 /en$request_uri;
}

location = /my-page {
    return 301 /en/my-page;
}

location /en/ {
   ...
}



来源:https://stackoverflow.com/questions/60414527/redirect-domain-to-default-language-nginx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!