Arkuen
Arkuen

Reputation: 359

Clean/Pretty URLs with htaccess (special case)

I've got this URL going on:

http://domain.com/edit.php?id=123

I've been searching and so far, everything I find is teaching me to modify htaccess so that it becomes:

http://domain.com/123/

My problem is, I also have http://domain.com/delete.php?id=123

So wouldn't it conflict since they would both be rewritten by htaccess to the same (http://domain.com/123/) ?

How can I make it so that

http://domain.com/edit.php?id=123 --> http://domain.com/edit/123 http://domain.com/delete.php?id=123 --> http://domain.com/delete/123 http://domain.com/page.php --> http://domain.com/page

Upvotes: 1

Views: 93

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

So wouldn't it conflict since they would both be rewritten by htaccess to the same (http://domain.com/123/) ?

Yes, there is no way to tell if "123" should be routed to "edit" or "delete". You have to add the prefix like you've suggested. Via these rules in the htaccess file in your document root:

Options +FollowSymLinks -Multiviews
RewriteEngine On

RewriteRule ^delete/([0-9]+)/? /delete.php?id=$1 [L,QSA]
RewriteRule ^edit/([0-9]+)/? /edit.php?id=$1 [L,QSA]

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

Additionally, you can add these to externally redirect browsers to the nicer looking URL

RewriteCond %{THE_REQUEST} \ /+([^.]+)\.php\?id=([0-9]+)
RewriteRule ^ /%1/%2? [L,R=301]

RewriteCond %{THE_REQUEST} \ /+([^.]+)\.php
RewriteRule ^ /%1 [L,R=301]

Upvotes: 1

Related Questions