Answer the question
In order to leave comments, you need to log in
How to make a redirect depending on the browser language?
I am moving a website from one server to another.
Apache was used on the old server, Nginx on the new one.
Previously, there was this .htaccess:
RewriteEngine on
# редирект на русскоязычную версию сайта
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteCond %{HTTP:Accept-Language} (ru|uk|be|kk|mo|ka|et|bg|az) [NC]
RewriteRule .* http://ru.site.net/ [R=302,L]
# редирект на англоязычную версию сайта для всех остальных языков
RewriteCond %{REQUEST_URI} ^/$ [NC]
RewriteRule .* http://en.site.net/ [R=302,L]
server {
listen 80;
listen [::]:80;
root /home/site/www/site.net;
index index.php index.html index.htm index.nginx-debian.html;
server_name site.net www.site.net;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
server {
listen 80;
listen [::]:80;
root /home/site/www/ru.site.net;
index index.php index.html index.htm index.nginx-debian.html;
server_name ru.site.net www.ru.site.net;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
server {
listen 80;
listen [::]:80;
root /home/site/www/en.site.net;
index index.php index.html index.htm index.nginx-debian.html;
server_name en.site.net www.en.site.net;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Answer the question
In order to leave comments, you need to log in
Did it like this:
map $http_accept_language $lang {
default en;
~ru ru;
~uk ru;
~be ru;
~kk ru;
~mo ru;
~ka ru;
~et ru;
~bg ru;
~az ru;
}
...
server {
listen 80;
listen [::]:80;
root /home/site/www/site.net;
index index.php index.html index.htm index.nginx-debian.html;
server_name site.net www.site.net;
location = / {
if ($lang = 'ru') {
rewrite (.*) http://ru.site.net;
}
rewrite (.*) http://en.site.net;
}
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Train yourself to search and read the docks correctly. Nginx has an Accept Language module
From the docs:
Alternative
You can manage $language_suffix by this setting when you cannot add this module into your system.
# accept-language: en,en-US;q=0.8,ja;q=0.6
set $first_language $http_accept_language;
if ($http_accept_language ~* '^(.+?),') {
set $first_language $1;
}
set $language_suffix 'en';
if ($first_language ~* 'ja') {
set $language_suffix 'ja';
}
By default, the module is not built.
https://www.nginx.com/resources/wiki/modules/accep...
Good luck!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question