2

I've tried to remove the .php extension and keep the id query parameter, but I get a 404 error.

This is the URL:

example.com/folder/file.php?q=123

And I want it to be:

example.com/folder/file/123

Here is my .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^$1/(.*)$ /$1.php?q=$2
2
  • To clarify, you are actually making requests to URLs of the form /folder/file/123 (since .htaccess itself doesn't actually "change" the URL). The .htaccess file is presumably in the document root directory? Commented Jan 6, 2023 at 17:02
  • Do you need to also handle extensionless URLs without additional parameters? eg. /folder/file? Commented Jan 6, 2023 at 17:14

2 Answers 2

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

This would internally rewrite the URL from /folder/file/123 to /folder/file/123.php, which is obviously going to result in a 404. It would be preferable to test that the corresponding .php file exists, rather than testing that the request does not already map to a file.

I'm assuming the q URL parameter always takes a numeric value.

Try the following instead:

# Rewrite "/folder/<file>/<123>" to "/folder/<file>.php?q=<123>"
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)/(\d+)$ $1.php?q=$2 [L]

The NC flag is not required.


RewriteRule ^$1/(.*)$ /$1.php?q=$2

This rule doesn't make sense and is redundant.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming last path component makes query parameter q, you can use this rule:

RewriteEngine On

# ignore all files and directories from rewrite
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Add .php extension and use last component as parameter q
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+)/([\w-]+)/?$ $1.php?q=$2 [L,QSA]

# Add .php extension
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Comments

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.