0

Say I have a page testpage.php and I want to access it through localhost/testpage . I can't figure out the regex to get it to work.

When I use the following, I get a server error

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* "^[^0-9][A-z0-9_]+*.php"/$0 

However, when I specify the exact file it works.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* testpage.php/$0 

3 Answers 3

3

Try this:

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

the third line checks if the file actually exists before doing the rewrite to avoid errors

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

Comments

1
RewriteEngine On

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

It will rewrite the filename with .php extention

Comments

1

You cannot specify a regular expression in the replacement pattern. That's why it fails. In this line

RewriteRule .* "^[^0-9][A-z0-9_]+*.php"/$0 

You are telling Apache to rewrite anything ( .* ) to the literal "^[^0-9][A-z0-9_]+*.php"/, plus the zeroth matched string (which is an error anyway, because matches start from $1, then there is $2 etc.).

If you want to capture a match you must surround it with parentheses, like

(.*)

and then it will be available in the replacement string as $1.

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.