Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod-rewrite Trailing Slash Issue

Tags:

mod-rewrite

There doesn't seem to be much info on this topic so I'm going to outline my specific problem then maybe we can shape the question and the answer into something a bit more universal.

I have this rewrite rule

RewriteEngine On
RewriteBase /bookkeepers/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/?$ index.php?franchise=$1

Which is changes this URL

http://example.com/location/kings-lynn

Into this one

http://example.com/location/index.php?franchise=kings-lynn

The problem I am having is that if I add a trailing slash

http://example.com/location/kings-lynn/

then the query string is returned as

franchise=kings-lynn/

and for some reason none of my CSS and Javascript files are being loaded.

Any ideas?

like image 249
Binarytales Avatar asked Nov 24 '08 17:11

Binarytales


People also ask

How do you fix trailing slash issues?

A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.

How do I get rid of trailing slash?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

Does Google care about trailing slash?

Google does not care whether or not you use a trailing slash in your URLs. The thing that does matter is how you use them – Google counts each one as a different URL. https://www.example.com/safari and https://www.example.com/safari/ are two individual pages.

Is trailing slash required?

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. However, these are guidelines and not requirements.


1 Answers

As @Paul Tomblin said, the .+ is being greedy; that is, it's matching as much as it can.

^(.+[^/])/?$ tells it to match anything, followed by a character that isn't a /, then followed by an optional /. This has the effect of not capturing the trailing /.

The most probable reason your CSS and Javascript doesn't work is you're using a relative path, like src="my.js". When there's a trailing slash, it looks like a directory, so your browser will look for /location/kings-lynn/my.js. You can fix this simply by using an absolute path to your files (e.g. /location/my.js).

like image 193
Greg Avatar answered Sep 27 '22 23:09

Greg