首页 > 解决方案 > htaccess - 从 URL 中删除目录名称

问题描述

我有以下站点结构:

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

哪个有效,但需要确保它也保持不变

标签: .htaccessredirectdirectory

解决方案


您可以在站点根目录 .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/或其他任何地方。


推荐阅读