【问题标题】:Remove "/php/" subdirectory from URL with .htaccess使用 .htaccess 从 URL 中删除“/php/”子目录
【发布时间】:2021-06-24 20:03:49
【问题描述】:

我一直在尝试在我正在构建的网站上实现以下重写/重定向,但我很挣扎,无法在线找到正确的答案。

我想重写

http://www.example.com/php/someFile.php

收件人:

example.com/someFile

我已经设法在我的 .htaccess 根文件中使用以下代码实现了大部分预期结果,但我需要帮助删除 php 子目录:

RewriteEngine on

# remove www from url
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]

# redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]

# internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php  [L]

任何帮助将不胜感激。

【问题讨论】:

    标签: .htaccess redirect mod-rewrite url-rewriting friendly-url


    【解决方案1】:

    在您的站点根目录 .htaccess 中使用这种方式:

    RewriteEngine on
    
    # remove www from url
    RewriteCond %{HTTP_HOST} ^www\.(example\.com)$ [NC]
    RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    
    # redirect /php/file.php to /file
    RewriteCond %{THE_REQUEST} \s/+(?:php/)?([^.]+)\.php [NC]
    RewriteRule ^ /%1 [NE,L,R=301]
    
    # internally map /file to /php/file.php
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/php/$1.php -f
    RewriteRule ^(.+?)/?$ php/$1.php [L]
    

    请务必在清除浏览器缓存后进行测试。

    【讨论】:

      【解决方案2】:

      对于您显示的示例,您能否尝试以下操作。 请确保在测试您的 URL 之前清除您的浏览器缓存。

      RewriteEngine on
      
      # remove www from url
      RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
      RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301,NE]
      
      # redirect /file.php to /file
      RewriteCond %{THE_REQUEST} \s/php/file\.php\s [NC]
      RewriteRule ^ file [R=301]
      RewriteRule ^ php/file.php [L]
      

      【讨论】:

      • 我已经尝试了答案,现在我收到以下消息:已永久移动文档已移至此处。此外,在尝试使用 ErrorDocument 处理请求时遇到了 301 Moved Permanently 错误。 “这里”超链接指向同一个 URL。
      • @ConnorMcgrann,好的,你能试试我编辑的规则一次吗?请在测试您的 URL 之前清除您的浏览器缓存。请告诉我进展如何,谢谢。
      • 我使用了您编辑的规则,它产生了上面的错误消息。你还有什么建议吗?
      • /@ConnorMcgrann,您能告诉我您在这里点击的示例/示例网址吗?
      • 不幸的是,我使用的域是私有的,因为我正在为客户处理它,该域是 .co.uk 域,这足以让您继续吗?
      猜你喜欢
      • 2012-06-25
      • 2013-05-18
      • 2020-05-11
      • 2013-05-28
      • 2013-08-18
      • 2020-01-09
      • 1970-01-01
      • 2019-10-03
      相关资源
      最近更新 更多