.htaccess 文件中 RewriteRule 的 OR 语句

问题描述 投票:0回答:1

我看到这个问题,他们询问如何在

OR
语句中使用
RewriteCond
。但是,我需要知道如何为这两种情况编写
RewriteRule
。 基本上,我们的网站上有
.html
.php
文件(文件名仅使用一个扩展名)。通过浏览器访问 URL 时,每个 URL 都应该重写自己,而不需要各自的扩展名。

这是我尝试过的代码。根本不起作用。请帮忙。

# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC] [OR] 
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME} \.php$  [OR]  
RewriteCond %{REQUEST_FILENAME} \.html$
RewriteRule ^/?(.*)$ /$1.php 
RewriteRule ^/?(.*)$ /$1.html 

编辑:这是我尝试过的一种简单方法,实际上按预期工作。但是,当我尝试在表单的

validate.php
属性中链接
action
文件时,出现了问题。它被重定向到
example.com/validate
并且不起作用。在我们的其他网站上,重定向到
example.com/validate
按预期工作,其中我们只有
.php
文件。

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f [NC]
RewriteRule ^ %{REQUEST_URI}.html [L]

RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
.htaccess url
1个回答
0
投票

见下图:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

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

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

第一个

RewriteCond
RewriteRule
检查请求的 URL 是否映射到现有目录或文件。如果是,则不再进行进一步重写([L] 标志)。

下一组检查所请求的 URL(减去扩展名)是否存在

.html
文件。如果是,它会在内部重写该文件。

最后一组的作用相同,但对于

.php
文件。

© www.soinside.com 2019 - 2024. All rights reserved.