Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 697
dvlden Avatar asked Mar 11 '26 09:03

dvlden


1 Answers

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.

like image 142
anubhava Avatar answered Mar 13 '26 05:03

anubhava