Jules
Jules

Reputation: 275

Using mod_rewrite to allow friendly URL with or without slash

I am trying to create a mod_rewrite rule that will create a friendly URL that can be used with or without a trailing slash.

eg. domain.com/index.php?id=421 to be accessible by a user entering domain.com/421 or domain.com/421/ .

I currently have the (rather simplistic looking) rule:

RewriteEngine On
RewriteRule /(.*)$ /index.php?id=$1  

which works fine so long as there is a trailing slash but if the URL is entered without one is is re-written to domain.com/domain.com/index.php?id=421

I'm completely out of my depth here so any help would be greatly appreciated.

Upvotes: 0

Views: 129

Answers (1)

Jules
Jules

Reputation: 275

OK, I fixed this. Firstly the reason I ended up going round in circles for soooo long was that my browser was caching the .htaccess file (didn't know they did that!) and so whatever I tried had little effect! Once I had worked that out resolving the problem was a breeze thanks to all I had read during my many hours of frustration. My solutions is :-

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301] 
RewriteRule (.*)/ index.php?id=$1 [L]

If anyone needs an explanation of this code most of it is covered at http://enarion.net/web/htaccess/trailing-slash/.

Upvotes: 1

Related Questions