【问题标题】:mod_rewrite - How to keep rewritten addresses without changing html linksmod_rewrite - 如何在不更改 html 链接的情况下保留重写的地址
【发布时间】:2014-07-21 18:06:39
【问题描述】:

假设我有一个包含给定网站的网站: 索引.php 信息.php

为了隐藏 URL 的“index.php”部分并将“info.php”更改为“info”,我创建了以下 .htaccess:

RewriteEngine On
RewriteRule ^info$ info.php
RewriteRule ^.$ index.php

当我直接在地址栏中输入新的 URL 时它工作得很好,但在 index.php 中我有:

<a href="info.php">

因此,当我单击链接时,它会将我定向到信息页面并在 URL 中显示“info.php”。如果单击链接后只想在 URL 中看到“信息”,是否必须更改 HTML 代码中的链接?或者有没有办法让 .htaccess 文件自动完成?

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    您可以将此代码放入您的DOCUMENT_ROOT/.htaccess 文件中以自动更改这些链接:

    RewriteEngine On
    RewriteBase /
    
    # To externally redirect /dir/file.php to /dir/file
    RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC]
    RewriteRule ^ /%1 [R=301,L,NE]
    
    # To internally forward /dir/file to /dir/file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
    RewriteRule ^(.+?)/?$ /$1.php [L]
    

    但强烈建议在您的 HTML 页面中更改这些链接以避免一次外部重定向。

    【讨论】:

      猜你喜欢
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2015-10-17
      • 1970-01-01
      相关资源
      最近更新 更多