skip to Main Content

I’m trying to add a language prefix to my pages through mod_rewrite
eg:

https://example.com/ > https://example.com/en/

and internally it need to translate to `https://example.com/?language=en
I’ve managed to do it for the base url, but when I try to do it with some other redirect implied, it’s always end in an infinite loop.
eg:

https://example.com/product-p-22.html > https://example.com/en/product-p-22.html

and internally became `https://example.com/product_info.php?product_id=22&language=en
here is my actual config:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/(en|fr)/
RewriteCond %{REQUEST_URI} .(php|html) [OR]
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{QUERY_STRING} !language=
RewriteRule ^(.*)$ en/$1 [L,R=301]
RewriteCond %{REQUEST_URI} !^/example
RewriteRule ^(.*)/$ index.php?language=$1&%{QUERY_STRING}
RewriteRule ^(.*)/(.*)-p-(.*).html$ product_info.php?products_id=$3&language=$1&%{QUERY_STRING}

I’ve tried many flags like L, END, DPI or some combination of those, but with no luck.
when I look at the debug logs, it seems to find the right url, but then restart parsing the default url:

pass through /var/www/example/product_info.php
init rewrite engine with requested uri /product-p-22.html
pass through /product-p-22.html

any though on what I’m doing wrong here?

Server version: Apache/2.4.41 (Ubuntu)

2

Answers


  1. Based on your shown samples, could you please try following. Please make sure you clear your browser cache before testing your URLs.

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^en [NC]
    RewriteRule ^(.*)$ en/$1 [NC,R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php?language=en [NC,QSA,L]
    
    RewriteRule ^([^/]*)/([^-]*)-p-([^.]*).html$ product_info.php?products_id=$3&language=$1& [NC,L,QSA]
    
    Login or Signup to reply.
  2. Have it this way in your site root .htaccess:

    RewriteEngine On
    
    RewriteCond %{THE_REQUEST} !s/+(en|fr)/ [NC]
    RewriteRule ^ /en%{REQUEST_URI} [NC,R=301,L]
    
    RewriteRule ^([a-z]{2})/[^-/]+-p-([^./]+).html?$ product_info.php?language=$1&products_id=$2 [L,QSA]
    
    RewriteRule ^([a-z]{2})/$ index.php?language=$1 [QSA,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search