1
votes

I'm not too used to work with htaccess files so I struggled for a while on this one :

I'd like to know how can I rewrite an URL (example.com/foo/bar) to (example.com/index.php?q=/foo/bar) AFTER adding a trailing slash (301 redirect) to the initial URL :

I know how to add the trailing slash alone :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://exemple.com/$1/ [L,R=301]

And how to rewrite to index.php :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L]

But I just can't figure how to do both at the same time...

Any help is more than welcome !

Pierre Fraisse

2
Just put both sets of line into one file. No need to repeat the RewriteEngine on part. I would however use ^(.+)$Gerben
Well, that's of course the first thing i tried :) but it doesn't work... However I noticed that putting the rewrite index.php first make the 301 redirect go to index.php?q=XXX instead of adding a trailing slash...Pierre Fraisse
The redirect should always come first. Could you explain what did not work? I assume both script are working on their own? I can't really see why it wouldn't work. The only thing I can think of, is that the php script doesn't like it when $_GET['q'] ends with a slash?Gerben
Indeed the 2 scripts are working on their own : the redirect one add the slash but I get a 404 error (of course ^^) and the rewriting one work but i don't have the slash at the end. What doesn't work when they are together is the redirect one. The rewriting is still working...Pierre Fraisse

2 Answers

2
votes

Try this in your .htaccess (I tested it as far as I could):

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L]

RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ $1/ [L,R=301]

RewriteRule ^(.*)$ index.php?q=$1 [L]
0
votes

You have an accepted answer here but I still like to answer this since actual answer is way more simpler that running it through multiple (and slow) redirects as in the other answer.

Put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php?q=%{REQUEST_URI} [L]