Hamid
Hamid

Reputation: 1760

htaccess clean url

I want to change my url to:

www.xxxx.com/en/ -> index.php?lang=en
www.xxxx.com/news -> index.php?mod=news

I use this code but it does not work:

RewriteCond %{REQUEST_URI} ^/(pe|en|fr|sp|ar)/$ 
RewriteRule ^([^/]*)/$ index.php?lang=$1

RewriteCond %{REQUEST_URI} !^/(pe|en|fr|sp|ar)$ 
RewriteRule ^([^/]*)$ index.php?mod=$1 

var_dump($_GET) result :

array(2) { ["mod"]=> string(9) "index.php" ["PHPSESSID"]=> string(32) "e7a5fc683653b7eea47a52dfc64cd687" }

I also use htaccess tester ( http://htaccess.madewithlove.be/ ) and all things were ok! :(

Upvotes: 0

Views: 894

Answers (3)

LazyOne
LazyOne

Reputation: 165088

This one works fine for me:

RewriteRule ^(pe|en|fr|sp|ar)/$ index.php?lang=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?!(?:pe|en|fr|sp|ar)/)([^/]*)$ index.php?mod=$1 [L]
  1. You definitely have to use [L] flag in such situations

  2. I got rid of RewriteCond in first rule -- the pattern is simple enough and no need in having separate condition (which means 2 matches has to be done instead of 1 in my implementation).

  3. In second rule use %{REQUEST_FILENAME} to check if requested resource (original or already rewritten) in not a real file/folder and only then rewrite. This will prevent that double rewrite that you facing.

  4. I have also got rid of RewriteCond here as rule is not too complex (it's more difficult to read, especially if your regex skills are not great, but it is working). This also makes my answer a bit different to already provided :)

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

You're capturing the index.php. Ignore existing files and directories, and stop processing rules with [L]

RewriteCond %{REQUEST_URI} ^/(pe|en|fr|sp|ar)/$ 
RewriteRule ^([^/]*)/$ index.php?lang=$1 [L]

# Don't rewrite index.php or other existing file/dir
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !^/(pe|en|fr|sp|ar)$ 
RewriteRule ^([^/]*)$ index.php?mod=$1 [L]

Upvotes: 1

Matchu
Matchu

Reputation: 85784

Both rules pass, and are therefore applied. The first rewrites /en/ to /index.php?lang=en. Then the second rule passes, and rewrites to /index.php?mod=index.php.

Use the [L] option to stop processing once a given rule passes:

RewriteCond %{REQUEST_URI} ^/(pe|en|fr|sp|ar)/$ 
RewriteRule ^([^/]*)/$ index.php?lang=$1 [L]

RewriteCond %{REQUEST_URI} !^/(pe|en|fr|sp|ar)$ 
RewriteRule ^([^/]*)$ index.php?mod=$1 [L]

Upvotes: 1

Related Questions