Home > front end >  .htaccess language based RewriteRule like example.com/en/
.htaccess language based RewriteRule like example.com/en/

Time:02-06

I'm trying to write redirect directives in the .htaccess to forward internally all user requests like this:

  • Every request in a language folder should redirect to the requested file with the language query string:
example.com/en/contact.php -> example.com/contact.php?lang=en
  • Redirect any request without language path to a default language folder like this:
example.com -> example.com/en
  • Remove trailing slash if the address is entered with it:
example.com/en/ to example.com/en
  • For the folder projects, every request should lead to the view-project.php file with the respective query strings:
example.com/en/projects/test -> example.com/view-project.php?lang=en&path=test

Here is my attempt, but it's not working without trailing slash on a request like: http://www.example.com/de and is not redirecting http://www.example.com to a default language folder.

RewriteEngine On

RewriteRule ^(en|de)/(.*)$ $2?lang=$1 [L,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^projects/([^/\.] )/?$ view-project.php?path=$1 [QSA,L]

How can I achieve this?

This is possible a duplicate and I apologize for that. I searched everywhere and read about 100 posts, but I did't found what I'm looking for.

CodePudding user response:

Try:

RewriteEngine On
RewriteBase /mysite.com/

RewriteCond %{HTTP:Accept-Language} (en|de) [NC]
RewriteRule ^ /%1/index.php [L]

RewriteCond %{HTTP:Accept-Language} (en|de)
RewriteCond %{DOCUMENT_ROOT}%1%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^(en|de)/(. )$ $2&lang=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^projects/([^/\.] )/?$ view-project.php?path=$1 [QSA,L]

CodePudding user response:

after struggling a while and with the help of someone else, here is the .htaccess file that works for me:

RewriteBase /example.com/
DirectorySlash Off
RewriteEngine On
RewriteOptions AllowNoSlash

RewriteRule ^$ de [R=301,L]

RewriteRule ^(de|en)/$ $1 [R=301,L]

RewriteRule ^(de|en)$ index.php?lang=$1 [L]

RewriteRule ^(de|en)/projects/(. ) view-project.php?lang=$1&path=$2 [L,QSA]

RewriteRule ^(de|en)/(. ) $2?lang=$1 [L,QSA]
  •  Tags:  
  • Related