Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mod_rewrite: add trailing slash?

I am using a .htaccess file to direct requests for a directory to a custom php file that provides info about that directory (and i want the url displayed by the browser to not change).

Here is the relevant part of the .htaccess file.

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ /myphp.php?url=%{REQUEST_URI} [QSA,L] 

This works well if you go to a directory and include a trailing slash:

http://domain.com/path/

But without the trailing slash, it doesn't

http://domain.com/path

The url (shown in the browser) turns into:

http://localhost:8888/path/?url=/path

I've tried fixing this by adding a rule above this rule:

RewriteCond %{REQUEST_FILENAME} -D
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]

But that isn't working for me.

How can I get .htaccess to add the trailing slash if it is omitted and then act just as if it had been there?

Thank you

Update: As requested, here is the whole thing.

<IfModule mod_rewrite.c>
RewriteEngine On

#force trailing slashes on real directories
RewriteCond %{REQUEST_FILENAME} -D
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]

#use the directory viewer on directories without an index page
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ /myphp.php?url=%{REQUEST_URI} [QSA,L]  

</IfModule>
like image 795
bkit Avatar asked Jun 28 '10 14:06

bkit


People also ask

How do you add a trailing slash to a URL?

A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.

How do I add a trailing slash to my WordPress URL?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash. Likewise, if it is not present there, the slash will be missing in your website's URLs.

What is a trailing slash in URL?

Historically, it's common for URLs with a trailing slash to indicate a directory, and those without a trailing slash to denote a file: http://example.com/foo/ (with trailing slash, conventionally a directory) http://example.com/foo (without trailing slash, conventionally a file)

What is RewriteCond and RewriteRule?

There are two main directive of this module: RewriteCond & RewriteRule . RewriteRule is used to rewrite the url as the name signifies if all the conditions defined in RewriteCond are matching. One or more RewriteCond can precede a RewriteRule directive.


1 Answers

This line:

RewriteCond %{REQUEST_FILENAME} -D

Should have been:

RewriteCond %{REQUEST_FILENAME} -d
like image 141
bkit Avatar answered Sep 23 '22 17:09

bkit