Nginx + WordPress language redirect

flero asked:

i am currently trying to configure an Nginx installation with WordPress multisite used for language support.

The multisite is configured:
mysite.com (not used)
mysite.com/it
mysite.com/en

Basically i want to add a default language and redirect if i find english. The site is actually on an Apache installation so we use:

RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^$ /en/ [L,R=301]

RewriteRule ^$ /it/ [L,R=301]

for the actual redirect.

I’m trying to replicate that with nginx, without any luck. So far i added:

map $http_accept_language $lang {
    default it;
    ~en en;
}

server {

 listen       80;
 server_name  mysite.com;
 access_log  /var/log/nginx/logs/mysite-access.log ;
 error_log /var/log/nginx/logs/mysite-error.log ;

 location / {
    root   /var/www/html/mysite;
    index  index.php index.html;
    try_files $uri $uri/ /index.php?$args;
    rewrite ^ /$lang/ permanent;
 }    

#Other rules used by wordpress and plugins
}

This results in “The page does not redirect correctly” error.

Any tips on how to solve the issue?

Thanks.

My answer:


Here is a problem:

    rewrite ^ /$lang/ permanent;

You are rewriting every request, not merely requests to the home page, because every request has a beginning.

There are (at least) two ways to fix this. You can use either:

  1. Rewrite only requests for the home page.

    rewrite ^/$ /$lang/ permanent;
    
  2. Use a specific location that matches only the home page:

    location = / {
        return 301 /$lang/;
    }
    

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.