Grouping file extensions for re-writing URL's [.htaccess]

痞子三分冷 提交于 2019-12-25 05:32:28

问题


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]

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/30678253/grouping-file-extensions-for-re-writing-urls-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!