I need some help with rewriting different URL's for my website. It is a multilanguage site so that complicates it a bit. I have managed to get some things work. This is what my code does so far:
- Define the RewriteBase (because localhost and production server have different bases)
- Rewrite www.mysite.com to www.mysite.com/en/ (or a different language, depending on 'lang' parameter)
- Redirect non-www to www
- Remove index.php from URL
What I want
But I have two problems with the code:
- It redirects to http://www.example.com/en/?lang=en. But I don't want that last parameter and I can't figure out with my basic skills how to hide the 'lang'. How to prevent adding that parameter to the URL?
- When I go to, lets say, http://www.example.com/?page=news the /en/ is not added to the URL. How to fix that? It should ALWAYS, in every, url, add the language after the domain.
Besides that, I would like to have two additional rewriterules but I don't want my htaccess to be a mess. So I hope someone can point me in the right direction. What is the best way to do this in my htaccess?
The parameter 'page' contains the page that is displaying and should be rewrited: http://www.example.com/en/index.php?page=info -> http://www.example.com/en/info/ (I already figured out how to hide the index.php, see code below)
My News page (http://www.example.com/en/index.php?page=news&id=2452&news=lorem-ipsum) should be rewrited to http://www.example.com/en/news/2452/lorem-ipsum/.
And for all of these rules: the URL should end with /, if it doesn't, it should add it: so http://www.example.com/en/news -> http://www.example.com/en/news/.
This is my code now:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
# SET REWRITEBASE VARIABLE
RewriteCond %{HTTP_HOST} !=localhost
RewriteRule ^ - [E=FRB:/]
RewriteCond %{HTTP_HOST} =localhost
RewriteRule ^ - [E=FRB:/www.example.com/]
## REWRITE FOR LANGUAGE ##
# empty url -> redirect to en/
RewriteCond %{QUERY_STRING} !lang=(en|de)
RewriteRule ^$ %{ENV:FRB}en/ [R=301,L]
# url is ONLY '/en' or '/de' -> redirect to /en/ or /de/ (adding slash)
RewriteRule ^(en|nl)$ %{ENV:FRB}$1/ [R=301,L]
# now all urls have en/ de/ -> parse them
RewriteRule ^(en|nl)/(.*)$ %{ENV:FRB}$2?lang=$1&%{query_STRING} [L]
## REWRITE NON-WWW TO WWW (EXCEPT ON LOCALHOST) ##
RewriteEngine On
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^(.*)\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
## REMOVE INDEX.PHP FROM URL ##
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L,QSA]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]
Thank you very much for helping me out! If you have questions, please let me know.