【问题标题】:htaccess - remove directory names from URLhtaccess - 从 URL 中删除目录名称
【发布时间】:2019-06-19 10:41:32
【问题描述】:

我的网站结构如下:

- index.php
- css/
- js/
- img/
- content/
  - product/
    - product-page-1.php
    - product-page-2.php 
  - static/
    - faqs.php
  - landing/
    - homeware-gifts.php 
    - stationary/
      - desks.php 

所以目前我的一些网址是这样的,但我需要隐藏 contentproduct, static, landing 目录

产品

mysite.com/content/product/product-page-2.php

mysite.com/product-page-2

静态

mysite.com/content/static/faqs.php

mysite.com/faqs

着陆

mysite.com/content/landing/homeware-gifts.php
mysite.com/content/landing/stationary/desks.php

mysite.com/homeware-gifts
mysite.com/stationary/desks

注意我也想隐藏 .php 扩展名,我目前正在使用这个:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

这可行,但需要确保它也保持不变

【问题讨论】:

  • 所以如果 URL 是mysite.com/aboutus 那么aboutus.php 可以在product/static/landing/ 中或找不到。这可以做到,但效率会有点低,因为它需要检查 3 个目录中是否存在 php 文件。
  • 如果更简单,我可以将所有 php 页面文件移动到 content 目录中吗?所以忽略产品/静态/登陆目录
  • 是的,那太好了,我会根据这个假设发布答案。

标签: .htaccess redirect directory


【解决方案1】:

您可以在站点根目录 .htaccess 中使用这些规则:

RewriteEngine On

## hide .php extension
# To externally redirect /content/file.php to /file
RewriteCond %{THE_REQUEST} \s/+site1/content/(.+?)\.php[\s?] [NC]
RewriteRule ^ /site1/%1 [R=301,NE,L]

## To internally rewrite /file to /content/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/site1/content/$1.php -f
RewriteRule ^site1/(.+?)/?$ site1/content/$1.php [L,NC]

这假设site1/ 或其他任何地方都没有.htaccess

【讨论】:

  • 我已经尝试过了,但是当我转到 mysite.com/content/product-page-1 时,我得到了响应“未找到,在此服务器上找不到请求的 URL mysite.com/product-page-1。我错过了什么吗?
  • 为什么在 URL 中使用/content/。您应该打开mysite.com/product-page-1 URL,product-page-1.php 应该放在content/ 目录中。
  • 对不起我的错误。另外我想我可能已经意识到了错误。我正在处理另一个子目录,而不是根目录。您是否能够调整您的答案以供工作:mysite.com/site1/content/product-page-1 可以通过mysite.com/site1/product-page-1 访问?很抱歉造成混乱
  • 我会把 .htaccess 放到根目录下,即mysite.com
  • 像魅力一样工作。谢谢!!
【解决方案2】:

假设你的网络服务器是 Apache2,你必须把它放在你的虚拟主机配置中:

    <Directory "/path/to/webroot">
         Options Indexes FollowSymLinks MultiViews
         AllowOverride all
         Order allow,deny
         allow from all
    </Directory>

然后你就可以玩 .htaccess,首先你必须添加

    Options +FollowSymlinks
    RewriteEngine On

在所有 .htaccess 中并使用此模板:

    RewriteRule ^MySuperRewritePath$  /my/path/without/rewrite.php [L]

(据我所知,您不需要在重写的 URL 中添加 .php,这样就可以满足您的需求)

如果您想了解更多信息,请查看official docs

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2020-01-31
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多