首页 文章

.htaccess检查文件是否存在于多个子文件夹中并重写

提问于
浏览
1

假设我在Apache服务器上有一个具有此文件夹结构的静态网站:

http://www.example.com
|    
+-- /news/
|  |  
|  +-- page1.html
|  +-- page2.html
|  +-- ...
|
+-- /otherstuff/

/ news /文件夹中页面的URL是:

http://www.example.com/news/page1.html  
http://www.example.com/news/page2.html

现在,/ news /文件夹中的文件数量正在增长,我想在/ news /中创建新的子文件夹,并在这些新目录中分割文件,但我还想在网址中隐藏子文件夹名称 .

新的文件夹结构将是:

http://www.example.com
|    
+-- /news/
|  |  
|  +-- /subfolder1/
|  |   |
|  |   +-- page1.html
|  |
|  +-- /subfolder2/
|  |   |
|  |   +-- page2.html
|  +-- ...
|
+-- /otherstuff/

the urls of the pages have to remain the same

http://www.example.com/news/page1.html  
http://www.example.com/news/page2.html

not

http://www.example.com/news/subfolder1/page1.html  
http://www.example.com/news/subfolder2/page2.html

有没有办法在.htaccess中使用重写规则来实现这个结果?

我读过这个问题:How to use mod_Rewrite to check multiple folders for a static file

但是接受的答案对我不起作用 .

提前感谢任何建议 .

1 回答

  • 1

    您可以在/news/.htaccess中使用以下规则:

    RewriteEngine on
    
    RewriteCond %{DOCUMENT_ROOT}/subfolder/$1.html -f
    RewriteRule ^(.*?)\.html$ /news/subfolder/$1 [L]
    

    如果file.html存在于 /news/subfolder/ 中,则会将 /news/file.html 重写为 /news/subfolder/file.html .

    如果您的htaccess是root用户,则可以尝试以下操作

    RewriteEngine on
    
    RewriteCond %{DOCUMENT_ROOT}/news/subfolder/$1.html -f
    RewriteRule ^news/(.*?)\.html$ /news/subfolder/$1.html [L]
    

    如果上面的示例失败,您可以在root或news / .htaccess中尝试:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(?:news/)?(.*?)\.html$ /news/subfolder/$1.html [L]
    

相关问题