dvlden
dvlden

Reputation: 2462

Add trailing slash for specific rewritten query

I am working on an "ManualTranslation" class and I am stuck at .htaccess part.

I am trying to rewrite this query ?language=xx into /xx/ only.

So far I manage to make it work, not sure if it's any good or proper... But it is missing one thing for sure. If for some reason – someone try to select language manually by saying:

http://domain.com/it and forgets to add trailing slash, my .htaccess pieces fails. So it should add automatically that trailing slash if it's missing from this query parameter.

RewriteEngine On
Options +FollowSymlinks
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z]{2})/(.*)$  $2?language=$1 [QSA]

So for now, this only works this way: http://domain.com/it/ but not http://domain.com/it because of missing trailing slash which should be there.

If anyone can tell me what am I missing?


Also I am wondering if there is a chance to remove that rewritten query string with php if it fails to find the language. Right now I am just basically redirecting back to current file and I am not satisfied with it...

if ( isset($query) && !$this->isAllowed($query) )
{
    header("Location: {$_SERVER['PHP_SELF']}");
    exit;
}

Upvotes: 3

Views: 87

Answers (2)

anubhava
anubhava

Reputation: 785491

You can tweak your current rule to allow URLs not ending with /:

RewriteEngine On
Options +FollowSymlinks
RewriteBase /

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{THE_REQUEST} \s/+.*?[^/][?\s]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]{2})(/.*)?$ $2?language=$1 [QSA,L]

However keep in mind that a URL like http://domain.com/contacts will remain unaffected with above rule and you won't have language parameter populated.

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80649

Try this:

RewriteCond ^([a-z]{2})$ /$1/ [R=301,L,NC]

Put it just after your RewriteBase line.

Upvotes: 0

Related Questions