skip to Main Content

I have recently localized my php webpage with Gettext in a VPS running LEMP Debian 10 (PHP 7.3.27-1~deb10u1). The localized versions of the pages have the following URLs:

example.com/index.php?lang=es_ES

and

example.com/index.php?lang=en_GB

and so on.

I am trying get Nginx to rewrite the URL requests to fake folders in the following way:

example.com/en/index.php to=> example.com/index.php?lang=en_GB

example.com/es/index.php to=> example.com/index.php?lang=es_ES

and

example.com/en/manage/index.php to=> example.com/manage/index.php?lang=en_EN

example.com/es/manage/index.php to=> example.com/manage/index.php?lang=es_ES

And so on.
I have tried other solutions with no success. My Nginx server block configuration is as follows:

server {

    root /var/www/example.com;
    index index.html index.htm index.php;

    server_name example.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

    location ~ /(.*)$ {
        try_files $uri $uri/ /profiles.php?user-id=$1; #pretty urls for user profiles
    }

    listen 443 ssl;
}

There is already a rewrite in place: example.com/123 => example.com/profiles.php?user-id=123. I’d appreciate some insight on making the desired rewrites to work, without affecting the one already in place.
Thanks

2

Answers


  1. You can try this:

    map $lang $locale {
        en      en_GB;
        es      es_ES;
    }
    
    server {
    
        root /var/www/example.com;
        index index.html index.htm index.php;
    
        server_name example.com;
    
        rewrite ^/(?<lang>en|es)(?<suffix>/.*) $suffix?lang=$locale;
    
        location ~ .php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        }
    
        location ~ /(.*)$ {
            try_files $uri $uri/ /profiles.php?user-id=$1; #pretty urls for user profiles
        }
    
        listen 443 ssl;
    }
    

    I removed location / { try_files $uri $uri/ =404; } because

    • try_files $uri $uri/ =404; is default nginx behavior;
    • location ~ /(.*) will math any request (regex locations have greater priority than prefix ones) and will overtake any request except those ending with .php (regex locations are checked from first to last).
    Login or Signup to reply.
  2. Use a rewrite statement to remove the prefix and add the language argument. You probably need two rewrite statements as the language arguments are unique.

    There are a number of ways to structure this, for example using separate prefix locations:

    location ^~ /en/ {
        rewrite ^/en(/.*)$ $1?lang=en_GB last;
    }
    location ^~ /es/ {
        rewrite ^/es(/.*)$ $1?lang=es_ES last;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search