Sachin
Sachin

Reputation: 1303

How to set rewrite rule in .htaccess for the 'pagename/id'?

I have used the following code in .htaccess,

Options +FollowSymlinks
RewriteEngine on

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user-projects/([0-9]+)/?$ user-projects.php?uid=$1 [L,QSA]

This above code works for the url mydomain.com/pagename but if the url is like mydomain.com/user-projects/1 it gives '500 internal server error'

Can anybody tell me where I am doing wrong here?

Thanks.

Upvotes: 2

Views: 738

Answers (2)

Jon Lin
Jon Lin

Reputation: 143856

The reason you get a 500 error is because the first rule that you apply is blindly adding a .php extension to whatever that isn't a file. So /user-projects/1/ matches the first rule and gets a php extension tacked onto the end, and then the same thing happens again, and again.

You should either swap the order of the two rules, or make your php extension rule more precise:

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

That checks first that if you add a .php to the end, it actually points to a file that exists.

Upvotes: 2

Chris Wheeler
Chris Wheeler

Reputation: 1717

You have a forwardslash at the end of your rule, so it will match

mydomain.com/user-projects/1/

but not

mydomain.com/user-projects/1

You also don't need the question mark, so the correct rule would be

RewriteRule ^user-projects/([0-9]+)$ user-projects.php?uid=$1 [L,QSA]

Upvotes: 0

Related Questions