Reputation: 29
When I request my website, I'm trying to add trailing slash to the URL and then pass it to index.php as parameter using mod_rewrite.
My .htaccess file looks like this:
RewriteEngine On
#Add trailing slash
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ /$1/ [R]
#Pass to index.php
RewriteRule ^(.*)/$ index.php?p=$1
And in my index.php file just outputs the parameter:
<?php echo $_GET["p"]; ?>
But when I type to the adress bar anything except http://mydomain.com/, for example http://mydomain.com/contact, the php always outputs http://mydomain.com/index.php
. So http://mydomain.com/index.php
was somehow passed as the parameter instead of the requested page such as contact
, but I don't know why...
Also, when I edit
RewriteRule ^(.*)/$ index.php?p=$1
to
RewriteRule ^(.*)/$ /index.php?p=$1
and I type URL e.g. mydomain.com/contact
Apache gives me 302 Found and a link to where it was moved, but it links to the same page...
Any Ideas?
Thanks.
Upvotes: 0
Views: 2024
Reputation: 14237
Apache has a nice long writeup for this specifically.
Trailing Slash Problem
Every webmaster can sing a song about the problem of the trailing slash on URLs referencing directories. If they are missing, the server dumps an error, because if you say /~quux/foo instead of /~quux/foo/ then the server searches for a file named foo. And because this file is a directory it complains. Actually it tries to fix it itself in most of the cases, but sometimes this mechanism need to be emulated by you. For instance after you have done a lot of complicated URL rewritings to CGI scripts etc. Solution:
The solution to this subtle problem is to let the server add the trailing slash automatically. To do this correctly we have to use an external redirect, so the browser correctly requests subsequent images etc. If we only did a internal rewrite, this would only work for the directory page, but would go wrong when any images are included into this page with relative URLs, because the browser would request an in-lined object. For instance, a request for image.gif in /~quux/foo/index.html would become /~quux/image.gif without the external redirect!
So, to do this trick we write:
RewriteEngine on
RewriteBase /~quux/
RewriteRule ^foo$ foo/ [R]
The crazy and lazy can even do the following in the top-level .htaccess file of their homedir. But notice that this creates some processing overhead.
RewriteEngine on
RewriteBase /~quux/
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R]
It can be found here:
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
Upvotes: 1