用子目录重写url

时间:2018-04-03 21:02:13

标签: php apache .htaccess mod-rewrite

我在网络目录中有这个域的域主项目。现在我需要在域的根目录的子目录中放置类似的项目。

domain.com
|-web
|   |-index.php
|   |-assets
|
|-subdirectory
|   |-web
|       |index.php
|       |-assets

第一个项目domain.com/homepage的示例网址是使用htaccess重写到domain.com/web/index.php?url=homepage。资产网址将重写为资产目录。

/。htaccess的

RewriteEngine On
RewriteRule ^(.*)$ web/$1 [L]

/web/.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} \.(gif|png|jpe?g|ico|swf|js|css)$ [NC]
RewriteRule .* - [R=404,L]

# rewrite assets version to orginal location
RewriteCond %{REQUEST_URI} assets/([0-9]+)/
RewriteRule ^assets/([0-9]+)/(.*)$ assets/$2

RewriteCond %{REQUEST_URI} !\.(gif|jpg|png)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?url=$1 [L,QSA]

它运行良好,但如何扩展此htaccess或在子目录中添加另一个.htaccess来重写子目录网址?

示例 domain.com/subdirectory/homepage sholud重写为 domain.com/subdirectory/web/index.php?url=homepage

SOLUTION:

/。htaccess /subdirectory/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ web/$1 [L,QSA]
</IfModule>

/web/.htaccess /subdirectory/web/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} \.(gif|png|jpe?g|ico|swf|js|css)$ [NC]
    RewriteRule .* - [R=404,L]

    # rewrite assets version to orginal location
    RewriteCond %{REQUEST_URI} assets/([0-9]+)/
    RewriteRule ^assets/([0-9]+)/(.*)$ assets/$2

    RewriteCond %{REQUEST_URI} !\.(gif|jpg|png)$
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</IfModule>

最后:

domain.com/start 重写为 domain.com/web/index?url=start < / p>

domain.com/subdirectory/start 重写为 domain.com/subdirectory/web/index?url=start < / em>的

1 个答案:

答案 0 :(得分:1)

排除根目录上的/subdirectory重写,并在与根目录相同的文件夹htaccess下应用subdirectory规则。

<强> /。htaccess的

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/subdirectory
RewriteRule ^(.*)$ web/$1 [L]