重写规则以隐藏扩展名 .htaccess

Rewrite rule to hide extension .htaccess

我试图从 link

中隐藏 .php 文件的扩展名

例如www.example.com/about.php 显示www.example.com/about

我做了什么

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

而且效果很好。

但我还有一个 link example.com/news.php?id=45 按照上面的规则,我可以访问link like

example.com/news?id=45 without .php

但是我想隐藏id=45我想要这样example.com/news/45

我做了什么RewriteRule ^news.php?id=([0-9]+) /news/ [NC,L]

但是它不起作用我收到 500 内部服务器错误

试试这样:

# MultiViews must be disabled for "/news/45" to work
Options -MultiViews

RewriteEngine on

# Rewrite "/news/45" to "news.php?id=45"
RewriteRule ^news/(\d+)$ news.php?id= [L]

# Handle extensionless ".php" URLs
RewriteCond %{REQUEST_URI} !\.\w{2,3}$
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule (.*) .php [L]

您的 500 内部服务器错误实际上是由您“隐藏”.php 扩展的原始指令引起的,而不是由您的“新”指令(实际上没有做任何事情)引起的。您的原始指令会将 /news/45 的请求重写为 /news/45.php/news/45.php.php 等,从而创建一个重写循环(500 错误)。

my answer to the following question on ServerFault with a detailed explanation of this behaviour: https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error

what I did RewriteRule ^news.php?id=([0-9]+) /news/ [NC,L]

But It won't work I got 500 Internal Server Error

这个指令的逻辑是相反的,永远不会真正匹配请求的 URL(或者 anything),所以实际上不会 任何东西。但是,它在语法上没有问题,因此不会触发错误。

只要请求 /news/45(使用您的原始指令),无论该指令是否到位,都会发生 500 错误。