Search code examples
apache.htaccesshttp-redirectmod-rewritefriendly-url

.htaccess rule skipping $2 not matched uri segment from the url


I want below request and response

RewriteEngine On

#Check for files that do not contain the language string
RewriteCond %{REQUEST_URI} !^/[a-z]{2}/.*
RewriteRule ^(.*)$ https://%{HTTP_HOST}/en [R=301,L]

#Capture the language string and present it as the variable
RewriteCond %{REQUEST_URI} ^/([a-z]{2})/
RewriteRule ^([a-z]{2})/(.*)$ https://%{HTTP_HOST}/%1/%2 [R=301,L]

Tried with some changes in %2 segment uri but no help so far, anyone did this earlier? Let me know if more description required


Solution

  • With your shown samples/attempts, please try following. Please make sure to clear your browser cache before testing your URLs.

    Keep these Rules at the top of your .htaccess Rules file. I am assuming that you have rules present to serve your newly rewritten urls in your htaccess rules file.

    RewriteEngine ON
    ##1st kind of urls, to remove / from end of it.
    RewriteRule ^([a-zA-Z]{2})/?$ $1 [R=301,L]
    
    ##Handle https://example.com/de/fr/en/de/en TO https://example.com/de urls.
    RewriteRule ^([a-zA-Z]{2})/(?:[a-zA-Z]{2}/)*(?:[a-zA-Z]{2})/?$ $1 [R=301,L]
    
    ##Handle https://example.com/de/fr/path TO https://example.com/de/path urls.
    RewriteRule ^([a-zA-Z]{2})/(?:[a-zA-Z]{2}/)*(.*)/?$ $1/$2 [R=301,L]
    
    ##handle https://example.com/def/frq/path TO https://example.com/en urls here.
    RewriteRule ^([a-zA-Z]{3,})/.*$ en [R=301,L]
    

    Online demo for 3rd rule regex

    Online demo for 2nd rule regex



    EDIT: Or to check rules to start with a 2 letter specific language try following then, I have used en,us,de,fr languages, you can add more to it as per your need too.

    RewriteEngine ON
    ##1st kind of urls, to remove / from end of it.
    RewriteRule ^(en|us|de|fr)/?$ $1 [NC,R=301,L]
    
    ##Handle https://example.com/de/fr/en/de/en TO https://example.com/de urls.
    RewriteRule ^(en|us|de|fr)/(?:(?:en|us|de|fr)/)*(?:en|us|de|fr)/?$ $1 [NC,R=301,L]
    
    ##Handle https://example.com/de/fr/path TO https://example.com/de/path urls.
    RewriteRule ^(en|us|de|fr)/(?:(?:en|us|de|fr)/)*(.*)/?$ $1/$2 [NC,R=301,L]
    
    ##handle https://example.com/def/frq/path TO https://example.com/en urls here.
    RewriteRule ^([a-zA-Z]{3,})/.*$ en [R=301,L]