Last active
February 13, 2020 13:03
-
-
Save chesio/3fa0913531416bb1badb5f3261a8d15a to your computer and use it in GitHub Desktop.
Language redirect via .htaccess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### BEGIN Language redirect | |
## Example: | |
# - root URL: http://www.example.com/ | |
# - DE version: http://www.example.com/de/ | |
# - EN version: http://www.example.com/en/ | |
# - IT version: http://www.example.com/it/ | |
## Further notes | |
# Works also for websites with site root in subdirectory, eg. http://www.example.com/blog/ | |
# Works with both HTTP and HTTPS automatically, eg. https://www.example.com/ | |
# Order of language preference is: DE, EN, IT - it can be changed by reordering (de|en|it) regex below. | |
# DE is default language for users who speak neither DE, EN nor IT. | |
# Tell bots, that the content is based on language | |
<IfModule mod_headers.c> | |
Header append Vary Accept-Language | |
</IfModule> | |
<IfModule mod_rewrite.c> | |
# Store the current working (sub)directory and request URI. | |
# Examples: | |
# http://www.example.com/some/path/ => CWD is empty ; CRU = /some/path/ | |
# http://www.example.com/blog/some/path/ => CWD = /blog ; CRU = /some/path/ | |
# http://www.example.com/blog => CWD = /blog ; CRU = / | |
RewriteCond /$0#%{REQUEST_URI} ([^#]*)#(.*)\1$ | |
RewriteRule ^.*$ - [E=CWD:%2] | |
# Store the current request uri without any subdirectory. | |
RewriteCond /$0#%{REQUEST_URI} ([^#]*)#(.*)\1$ | |
RewriteRule ^.*$ - [E=CRU:%1] | |
# Set environment variable of current scheme for later usage via %{ENV:PROTO}. | |
RewriteRule ^ - [E=PROTO:http] | |
RewriteCond %{HTTPS} =on [OR] | |
RewriteCond %{ENV:HTTPS} =on | |
RewriteRule ^ - [E=PROTO:https] | |
# If user prefers one of existing languages, redirect properly... | |
RewriteCond %{ENV:CRU} ^/$ [NC] | |
RewriteCond %{QUERY_STRING} ^$ [NC] | |
RewriteCond %{HTTP:Accept-Language} (de|en|it) [NC] | |
RewriteRule ^$ %{ENV:PROTO}://%{HTTP_HOST}%{ENV:CWD}/%1/ [L,R=302] | |
# ...redirect all other languages or "no language" to German version. | |
RewriteCond %{ENV:CRU} ^/$ [NC] | |
RewriteCond %{QUERY_STRING} ^$ [NC] | |
RewriteRule ^$ %{ENV:PROTO}://%{HTTP_HOST}%{ENV:CWD}/de/ [L,R=302] | |
</IfModule> | |
### END Language redirect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment