.htaccess重定向HTML到PHP和访问PHP文件没有.PHP扩展名


.htaccess redirect html to php and access to php files without .php extension

我希望用这个。htaccess文件完成两件事。

1)所有对。html的请求都指向。php如。用户进入:http://www.mywebsite.com/contact.html浏览器加载:http://www.mywebsite.com/contact.php

2)请求http://www.mywebsite.com/contact将加载contact.php(这应该适用于所有页面,而不仅仅是联系人页面。

这是我的。htaccess文件。

Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L]

老实说,我不知道他们在做什么。我从我读到的一堆乱七八糟的文章中把它们混合在一起。

试试这样做。遵循注释线程了解安全含义,但这是您要求做的事情

RewriteEngine On
RewriteBase /
# Redirect HTML to PHP
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*).html$ $1.php [L]
# Otherwise, try PHP
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !'.php$
RewriteRule ^(.*)$ $1.php [L]
# Lastly, fallback to error page
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . 404.php [L]

我需要向你解释一些关于htaccess文件角色的事情;

在这个例子中,htaccess将尝试匹配模式,正如你在你的例子中需要的;

如果匹配一个模式,则会发生一些操作;

用()标记所有需要从url

中提取的数据

对于每个规则,第一个()将具有$1的id,第二个()将具有$2,依此类推

如果$1是'help',它可能会加载'help.php'文件,而不是'help.php'文件;它将加载您想要加载的文件;

using $1, $2…您可以将参数和值传递给真实的/翻译后的url请求

在我的例子中,我想一直使用index.php文件,你可以使用任何你需要的文件

Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteRule ^([a-zA-Z-]+)$ index.php?action=$1 [NC,L]
RewriteRule ^(member)-([0-9-]+)$ index.php?action=member&id=$2 [NC,L]
RewriteRule ^([a-zA-Z-]+)/([a-zA-Z-]+)-([0-9-]+)$ index.php?action=$1&saction=$2&sid=$3 [NC,L]
RewriteRule ^([a-zA-Z-]+)/([0-9-]+)$ index.php?action=$1&id=$2 [NC,L]
RewriteRule ^([0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/(.*).html$ index.php?action=details&id=$1&p1=$2&p2=$3&p3=$4 [NC,L]

如果您希望所有的。html文件都指向。php文件,一个简单的方法就是

RewriteRule (['w'd'-_]+)('.html)? $1.php [L]

这也允许你使用子目录

contact.html会重定向到contact.php

/subdir/page.html会重定向到/subdir/page.php,依此类推