apache.htaccessmod-rewrite

Redirect default language parameter to root with htaccess


I have been looking for a solution, but only found one similar case without an answer (unfortunately). Although the implementation is working, I am still missing one crucial aspect.

I am running a simple site (one php file) which loads the content based on the selected language and page. In order to have SEO friendly URLs, I am using the following .htaccess file:

RewriteEngine On
Options +FollowSymlinks

# 1. Redirect HTTP to HTTPS automatically (only if not in localhost)
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 2. Add a slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^./]+)$ $1/

# 3. Default homepage
RewriteRule ^([^./]+)/$ index.php?lang=$1&page=home

# 4. Language and page
RewriteRule ^([^./]+)/([^./]+)/$ index.php?lang=$1&page=$2

The result:

index.php?lang=en&page=services -> /en/services/
index.php?lang=nl&page=diensten -> /nl/diensten/
...

However, I would like English without the language subdirectory, while other languages retain the language subdirectory.

index.php?lang=en&page=services -> /services/
index.php?lang=en&page=about -> /about/
...

I could use "RedirectMatch 301 /en/(.*) /$1", but that is not the proper way.

How would I accomplish what I need?


Solution

  • Have it like this:

    RewriteEngine On
    Options +FollowSymlinks
    
    # 1. Redirect HTTP to HTTPS automatically (only if not in localhost)
    RewriteCond %{HTTP_HOST} !=localhost
    RewriteCond %{HTTPS} !on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    
    # 2. Add a slash
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^./]+)$ $1/
    
    # 3. Default homepage
    RewriteRule ^/?$ index.php?lang=en&page=$1 [L,QSA]
    
    # 4. default language to en
    RewriteRule ^([^./]+)/$ index.php?lang=en&page=$1 [L,QSA]
    
    # 5. Language and page
    RewriteRule ^([^./]+)/([^./]+)/$ index.php?lang=$1&page=$2 [L,QSA]