Forum Moderators: phranque

Message Too Old, No Replies

'domain.com/foo' = 404 but 'domain.com/foo/' works fine

How to set RewriteRules to make it work

         

guarriman

12:15 pm on Dec 12, 2007 (gmt 0)

10+ Year Member



Hi.

I created this .htaccess:
-----
RewriteRule ^([^/]+)/$ /page.php?id=$1 [L]
-------

And it works fine with:
[domain.com...] (it shows a webpage)

But it shows a 404 error page with:
[domain.com...]

I tried adding this line to .htaccess:
----
RewriteRule ^([^/]+)$ /page.php?id=$1 [L]
-----

But now it shows a 500 error webpage in both cases.

Any suggestion? Thank you very much.

jdMorgan

3:04 pm on Dec 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I tried adding this line to .htaccess:
 RewriteRule ^([^/]+)$ /page.php?id=$1 [L] 

But now it shows a 500 error webpage in both cases.

It is likely that if you examine your server error log file, you will find that it reports that the maximum internal redirection limit is reached for every request, resulting in a 500-Server Error.

This is because the pattern of this new rule matches anything that does not contain a slash -- including "/page.php" itself. So a request for any URL is rewritten to "/page.php", then that request is rewritten to "/page.php", and then that request is rewritten again to "/page.php" -- this repeats again and again, until the server gives up.

mod_rewrite in .htaccess is recursive, and this is the likely cause.

You have two choices, one simple, and one 'correct.' The simple solution is to modify the rule to accept either a trailing slash or no trailing slash, but also to reject requests for "page,php".


RewriteCond $1 ^!page\.php$
RewriteRule ^([^/]+)/?$ /page.php?id=$1 [L]

The problem with this is that you'd have two URLs pointed to the same content -- The much-discussed "duplicate content problem."

The correct solution would be to use a redirect to add a trailing slash if it is missing. Here the problem is one of 'design,' in that you need to be careful not to add trailing slashes to URLs that should not have one, such as robots.txt. I don't know all of your valid URLs, so all I can suggest is a generic solution, which you may have to adjust to better suit the URLs used on your site:


# If requested URL-path does not contain a ".' in final path-part or end with a slash
RewriteCond $1 !(^([^/]+/)*\.[^/.]+¦/)$
# and does not exist as a 'real' directory
RewriteCond %{REQUEST_FILENAME} !-d
# Redirect to add a trailing slash
RewriteRule (.*) http://www.example.com/$1/ [R=301,L]

Replace the broken pipe "¦" character with a solid pipe before use; Posting on this forum modifies the pipe characters.

This new rule should be placed ahead of your original internal rewrite rule.

Jim