Mode Rewrite; with/without trailing slash on end of url?
Asked Answered
G

3

12

I basically tried this mode_rewrite rule below. It works with a slash on the end but I want it to work whether it has a trailing slash on the end or not. Basically I want it like this as some people see it as normal with a slash on the end and others don't hence why I want it to work whether it's there or not.

RewriteRule ^signup/register(.[^/]*) /signup/register.php [NC]

Basically it will work like http://localhost/signup/register/ but if I remove the / from the end it gives 404 error.

Gad answered 22/2, 2011 at 15:56 Comment(0)
I
25

The subpattern .[^/]* requires at least one arbitrary character. In your case it’s probably that trailing slash.

You should better stick to one writing (either with or without trailing slash) and redirect th wrong writing to the proper, like:

# remove trailing slash
RewriteRule ^(.*)/$ /$1 [L,R=301]

# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*[^/]$ /$0/ [L,R=301]
Ideo answered 22/2, 2011 at 16:25 Comment(7)
Hi Gumbo, i just did that so it removes trailing slashes but wouldn't this cause more pressure on the server as it would have to remove trailing slashes?Gad
@PHPLOVER: You should serve the right URLs in the first place. These rules are only to fix those URLs that are misspelled.Ideo
Ok thanks i see what you mean, so basically change my urls to the new friendly ones in site without trailing slash and the only time apache will need to remove the / is if someone obviously includes it. Thanks i understand now.Gad
Sorry i was also meant to ask; should i setup a permanent redirect in .htaccess to friendly urls? reason why is in Google my site just uses like signup/register.php and not sure if i should do a permanent redirect ? i know how to do to them but thought i would ask. thanksGad
@PHPLOVER: Yes, you should already serve the documents containing the “new” URLs.Ideo
Thank you for this answer, I have been searching for a solution on this problem for a very long time.Necrophilia
@Ideo - Shouldn't remove trailing slash be like RewriteRule ^/?(.*)/+$ /$1 [L,R=301] or RewriteRule ^(.*)/+$ $1 [L,R=301] ? Will /%1 sometimes add duplicate / at the beginning of request? If not, why? Also /+$ have same effect like /$ What is auto rtrimming request?Pisciform
S
10

plain old regexes:

RewriteRule ^signup/register/?$ /signup/register.php [NC]
Sampan answered 12/3, 2014 at 11:14 Comment(0)
N
7
...    
RewriteRule ^(url-rewrite)/?$ page.php [NC]
...

The ? after / specifies that there can be none or one / after your url-rewrite, as such it would accept it with or without the trailing /

Nardone answered 28/11, 2017 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.