Grouping file extensions for re-writing URL's

2019-09-18 15:25发布

How can I group these two together; is it like ".(html|php)$" - please provide the code.

Note, the answer should work for all file extensions: what is your thoughts on removing every file extension; comment on the code used - as it is rare to find.

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
RewriteRule (.*)\.html$ $1 [R=301]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.html [L]

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

2条回答
放我归山
2楼-- · 2019-09-18 16:03

It seems like you pretty much answered your own question with

is it like ".(html|php)$"

You just had to try it. See if this will work for you to group html and php files.

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.(php|html)\ HTTP
RewriteRule ^ %1 [R=301,L]

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

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

There is one other possible solution. Is to not use the above code and use MultiViews. The one line of code below.

Options +FollowSymLinks +MultiViews
查看更多
Ridiculous、
3楼-- · 2019-09-18 16:04

Unfortunately, this is not possible.

The TestString part of RewriteCond can only contain a plain string, and allows for server variables (HTTP_REFERER, for example) and back-references ($1 and %1, for example).

As such, you cannot include an expression in the TestString - only the CondPattern (the second part of RewriteCond) allows for expressions.

The best that you can do is use an expression to strip out the extensions you don't want and then, for each extension you've stripped out, determine if it exists and rewrite accordingly - like so:

RewriteEngine on

# Step 1: Strip out extensions you don't want for files that actually exist

RewriteCond %{THE_REQUEST} ^GET\ (.*)\.(html|php)\ HTTP
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %1 [R=301,L]

# Step 2: For each extension stripped, rewrite for existing files

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

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

Side Note: It would be really great if Apache implemented some sort of looping in .htaccess files - it would help simplify this methodology. Unfortunately, this is not the case, and so the above is pretty much the best method.

查看更多
登录 后发表回答