1

I'm very new to URL rewriting. What I'd like to achieve is to have 2 main rules:

  1. Hide all .php extensions
  2. Rewrite domain.com/p.php?id=1 to domain.com/p/1

Here's what I have so far:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule   ^p/(.+)$   p.php?id=$1   [L]

This seemed to work at first: all .php extensions are hidden, and typing domain.com/p/1 displayed domain.com/p.php?id=1.

However, I've just realized that the PHP GET method on this page picks up a wrong value: whereas I want it to pick up 1, it actually picks up 1.php/1. I didn't notice it at first because the database query based on $_GET actually works, which seems odd to me now that I know the value is wrong.

How could I make the combination of these two rewrite rules work as intended?

Thank you!

1
  • RewriteRule ^(.*)$ $1.php is the poison poll here Commented May 6, 2014 at 18:53

2 Answers 2

1

Place this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

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

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

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]
Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Should I place this after the first rule I wrote, ^(.*)$ $1.php ? If I only keep this, it seems like domain.com/test does not rewrite to domain.com/test.php and throws a 404.
0

If you just want to rewrite the numerical values, you should restrict your second rule:

RewriteRule   ^p/(\d+)$   p.php?id=$1   [L]

1 Comment

Hi and thanks for you reply! However, this rule seems to trigger a 500 Internal Server Error. :-/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.