PinkTurtle
PinkTurtle

Reputation: 7041

.htaccess regular expression issue

I still have no answer about this so I'm posting it here.

I want to match an url in the form of root/language/sub/.../document in a .htaccess file and then rewrite it as root/sub/.../document.php?lang=language

Im close to hit but it seems my regexp doesn't 'catch' the input url. Here it is :

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond ^[a-z]{2}.*$/%{REQUEST_FILENAME}\.php -f
RewriteRule ^([a-z]{2})/(.*)$ $2.php?lang=$1

Can someone point me out what is wrong here ? I'm no expert in regexp nor apache rewrites.

Tyvm

* EDIT *

root stands for domain ie mydomain.net

Here are a few examples :

mydomain.net/fr/contact

should be rewriten to

mydomain.net/contact.php?lang=fr

and

mydomain.net/en/articles/view

should be rewriten

mydomain.net/articles/view.php?lang=en

etc...

Upvotes: 0

Views: 697

Answers (3)

Ωmega
Ωmega

Reputation: 43663

I believe you are looking for this configuration:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} ^(.*/|)(en|de|fr)/(.*)$ [NC]
RewriteCond %1%3.php -f
RewriteRule ^(.*/|)(en|de|fr)/(.*)$ $1$3.php?lang=$2 [NC,QSA,L]

Explanation:

RewriteCond %{REQUEST_FILENAME} !-d

Checks if requested url is not a directory. If yes, no rewriting will be processed.

RewriteCond %{REQUEST_FILENAME} ^(.*/|)(en|de|fr)/(.*)$ [NC]

Checks if url contains /xx/ part inside, where xx is one en, de or fr. Flag [NC] allows uppercase and lowercase charactes, so for example EN or Fr will be accepted. If there is no such "language" part in the url, no rewriting will be processed.

RewriteCond %1%3.php -f

Checks if %1%3.php file exists, where %1 is (.*/|) and %3 is (.*) matches from the previous RewriteCond ^(.*/|)(en|de|fr)/(.*)$. If such php file does not exist, no rewriting will be processed.

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

In the RewriteRule left condition will be matched if it came to this line, as it was already checked with RewriteCond, so now it will process rewriting to php file, adding lang part, but because there is also [QSA] flag, it will keep also other GET parameters, so lang will be added to existing parameters. Flag [L] says it is last rewriting rule that should apply and no more rewriting will be processed with this url.

Upvotes: 1

Andrew Cheong
Andrew Cheong

Reputation: 30273

What's wrong is the second RewriteCond. But your question is vague. If you mean you're trying to convert

root/foo/sub/.../something.php

to

root/sub/.../something.php?lang=foo

then start fidgeting with this:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^root/([^/]+)/sub/(.*)/%{REQUEST_FILENAME}$ root/sub/$2/%{REQUEST_FILENAME}?lang=$1

Upvotes: 0

Steve Robbins
Steve Robbins

Reputation: 13812

Well I'm not sure what root is doing in there, have you tried

RewriteRule ^root/([a-z]{2})/(.*)$ root/$2.php?lang=$1

Upvotes: 0

Related Questions