htaccess-从URL删除目录名称

时间:2019-01-25 15:07:55

标签: .htaccess redirect directory

我具有以下站点结构:

- 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]

哪个可以工作,但需要确保保持不变

2 个答案:

答案 0 :(得分: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]

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

答案 1 :(得分:0)

假设您的Web服务器是Apache2,则必须将其放入vhost配置中:

    <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