Home > OS >  Nginx redirect if language string not in url
Nginx redirect if language string not in url

Time:11-28

im not really familiar with nginx and redirects. And it might be a stupid question, but i hope someone can help me a bit with that.

Problem:
System has a global default locale "de" for domain.com/... But for one domain i need it as default language. Sadly it is not passible to change the default language in that CMS for a specific domain/site.

What i'm trying to do now:
If no locale is given in the url (domain.com/...) then nginx should redirect to domain/it/...

The other locales are /de and /en und should be untouched.

In the end this is what i'm trying to do:

domain.com/... -> domain.com/it/...

domain.com/de/... -> no redirect
domain.com/en/... -> no redirect
domain.com/en/... -> no redirect

The actual locations in the nginx config are:

location ~ /\. {
    access_log off;
    log_not_found off;
    deny all;
}

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

location ~ /_Resources/ {
    access_log off;
    log_not_found off;
    expires max;

    if (!-f $request_filename) {
        rewrite "/_Resources/Persistent/([a-z0-9]{40})/. \.(. )" /_Resources/Persistent/$1.$2 break;
        rewrite "/_Resources/Persistent(?>/[a-z0-9]{5}){8}/([a-f0-9]{40})/. \.(. )" /_Resources/Persistent/$1.$2 break;
    }
}


location / {
    try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
    include /usr/local/etc/nginx/fastcgi_params;
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.socket;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param FLOW_REWRITEURLS 1;
    fastcgi_param FLOW_CONTEXT Production;
    fastcgi_param FLOW_ROOTPATH /var/www/public_html/current/;
    fastcgi_param X-Forwarded-For $proxy_add_x_forwarded_for;
    fastcgi_param X-Forwarded-Port $proxy_port;
    fastcgi_param SERVER_NAME $http_host;
    fastcgi_param SERVER_PORT 443;
    fastcgi_split_path_info ^(. \.php)(.*)$;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 256 16k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
}

I hope it's understandable. :)

CodePudding user response:

There are a number of ways to achieve this. One simple solution is to use a prefix location for each language.

For example, replace your existing location / block with:

location / {
    return 307 /it$request_uri;
}
location /en {
    try_files $uri $uri/ /index.php?$args;
}
location /de {
    try_files $uri $uri/ /index.php?$args;
}
location /it {
    try_files $uri $uri/ /index.php?$args;
}
  • Related