9

In my htaccess I have some rewrited urls like these:

RewriteRule ^first-page$ /subdir/page.php?id_page=1 [QSA,L]
RewriteRule ^second-page$ /subdir/page.php?id_page=2 [QSA,L]
RewriteRule ^third-page$ /subdir/page.php?id_page=161 [QSA,L]

So the final result is: www.mywebsite.com/subdir/first-page

Now I would like to turn this into www.mywebsite.com/subdir/first-page/

Without the www.mywebsite.com/subdir/first-page giving a 404 error.

I tried this code after the url rewrites, but did not work:

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

Any suggestions? Thank you so much.

0

2 Answers 2

4

Try either

RewriteRule ^first-page/$ /subdir/page.php?id_page=1 [QSA,L]
RewriteRule ^second-page/$ /subdir/page.php?id_page=2 [QSA,L]
RewriteRule ^third-page/$ /subdir/page.php?id_page=161 [QSA,L]

or

RewriteRule ^first-page /subdir/page.php?id_page=1 [QSA,L]
RewriteRule ^second-page /subdir/page.php?id_page=2 [QSA,L]
RewriteRule ^third-page /subdir/page.php?id_page=161 [QSA,L]

The $ character tells Apache that this is the end of string and no more characters are expected. So you'll have to notify it to accept the slash at the end of the string, or to just be ready for any extra characters. You can use the ? flag to make the trailing slash not required, but accepted if present, e.g.:

RewriteRule ^first-page(/)?$ /subdir/page.php?id_page=1 [QSA,L]

So this won't let any other characters other than slash.

Hope this helps.

1
  • Thanks man! Adding (/)? at the end of the url solved the problem. However the preferred url is still the one without the slash. Could you please be so kind to tell me what could I do in order to make the URL with the slash as preferred?
    – F G
    Dec 20, 2012 at 14:39
0

Try this

RewriteRule ^first-page($|/$) /subdir/page.php?id_page=1 [QSA,L]
RewriteRule ^second-page($|/$) /subdir/page.php?id_page=2 [QSA,L]
RewriteRule ^third-page($|/$) /subdir/page.php?id_page=161 [QSA,L]

($|/$) - It allows both www.mywebsite.com/subdir/first-page and www.mywebsite.com/subdir/first-page/. It also ensures to not allow any unwanted urls like www.mywebsite.com/subdir/first-page/some-unwanted-text.

If you want the url with any parameters you could use as follows

RewriteRule ^third-page/?$ /subdir/page.php?id_page=161 [QSA,L]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.