PHPology
PHPology

Reputation: 1017

Htaccess language detection into specific folder where default EN language is not a folder

We have a 1 site where there is 4 languages, 3 of which are in subfolders i.e

/
  /de/
    index.html
    about-us.html
    ...

  /fr/
    index.html
    about-us.html
    ...

  /index.html
  /about-us.html
  ...

The default EN language is not in a folder like the others (above), they are at the root.

I have the htaccess code so far where I can detect the 3 languages via %{HTTP:Accept-Language} and it works a treat.

The problem I have is that when they click the EN option in the nav (/) the language detection kicks in via htaccess. How can I do it where if it has been clicked, I can tell .htaccess ignore the language detection?

I tried the HTTP_referer route where I said if there was no referrer detected, detect the language and continue and if the referer was the website name, ignore it. That didn't work (too many redirects).

I don't have server side support as the files are actually all html files built via Gulp but WORSE case can use it if no other solution is available.

Upvotes: 1

Views: 545

Answers (1)

PHPology
PHPology

Reputation: 1017

With a help from a friend, I ended up going down the route where I created a cookie via htaccess if a cookie with the value language was not found. Once the language was set and the user then went to view the English content (located in the root path where the htaccess lives) - htaccess will not do the language detection.

RewriteEngine On

# 301 = aggressively by the browser (use only on Production/Live)
# 302 = temporary redirect (use for development)
RewriteCond %{HTTP_COOKIE} !language=set [NC]
RewriteCond %{HTTP:Accept-Language} fr [NC]
RewriteRule ^$ /fr [co=language:set:%{HTTP_HOST}:10:/,L,R=302]

RewriteCond %{HTTP_COOKIE} !language=set [NC]
RewriteCond %{HTTP:Accept-Language} de [NC]
RewriteRule ^$ /de [co=language:set:%{HTTP_HOST}:10:/,L,R=302]

RewriteCond %{HTTP_COOKIE} !language=set [NC]
RewriteCond %{HTTP:Accept-Language} es [NC]
RewriteRule ^$ /es [co=language:set:%{HTTP_HOST}:10:/,L,R=302]

This vital snippet from this page (Tips for debugging .htaccess rewrite rules) also helped, I was using a 301 redirect locally, which was cached aggressively by the browser, making it difficult to debug.

301 Tip

  1. Do not use 301 until you are done testing I have seen so many posts where people are still testing their rules and they are using 301's. DON'T. If you are not using suggestion 1 on your site, not only you, but anyone visiting your site at the time will be affected by the 301. Remember that they are permanent, and aggressively cached by your browser. Use a 302 instead till you are sure, then change it to a 301

Upvotes: 2

Related Questions