将.htaccess转换为IIS 10的web.config并解决URL重写404问题
解决配置
以下是完整的web.config配置,包含所有重写规则、移除.php后缀的逻辑,同时修复/u/username/view路径的重写问题:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <!-- 处理 /p/xxx → post.php?user=xxx --> <rule name="Rewrite Post" stopProcessing="true"> <match url="^p/(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="post.php?user={R:1}" /> </rule> <!-- 处理 /register → register.php --> <rule name="Rewrite Register" stopProcessing="true"> <match url="^register$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="register.php" /> </rule> <!-- 处理 /login → login.php --> <rule name="Rewrite Login" stopProcessing="true"> <match url="^login$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="login.php" /> </rule> <!-- 处理 /u/username/view → messages.php?username=xxx --> <rule name="Rewrite User View" stopProcessing="true"> <match url="^u/(.*)/view$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="messages.php?username={R:1}" /> </rule> <!-- 处理 /u → messages.php --> <rule name="Rewrite Messages" stopProcessing="true"> <match url="^u$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="messages.php" /> </rule> <!-- 允许不带.php后缀访问页面 --> <rule name="Remove PHP Extension" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}.php" matchType="IsFile" /> </conditions> <action type="Rewrite" url="{R:1}" /> </rule> <!-- 可选:强制将带.php的URL重定向到无后缀版本,保证URL统一 --> <rule name="Redirect PHP to Clean URL" stopProcessing="true"> <match url="^(.*)\.php$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" /> </conditions> <action type="Redirect" url="{R:1}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
关键说明
- 修复
/u/username/view重写:原.htaccess规则存在语法错误,新增规则匹配/u/xxx/view格式,将用户名作为username参数传递给messages.php,需在messages.php中通过$_GET['username']获取该值。 - 移除.php后缀:通过两条规则实现——先让服务器接受无后缀请求并映射到对应.php文件;可选的重定向规则会将带.php的URL永久跳转到无后缀版本,避免重复内容。
- 解决404问题:所有重写规则都添加了判断逻辑,仅当请求路径不是真实文件或目录时才触发重写,不会干扰图片、CSS等静态资源的访问。
内容的提问来源于stack exchange,提问作者Lorenzo
相关产品推荐
相关产品推荐

