【问题标题】:.htaccess check if file exists in multiple sub-folders and rewrite.htaccess 检查文件是否存在于多个子文件夹中并重写
【发布时间】:2017-02-04 18:20:07
【问题描述】:

假设我在 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/ 中创建新的子文件夹并在这些新目录中拆分文件,但我还想隐藏 url 中的子文件夹名称。

新的文件夹结构将是:

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

页面的网址必须保持不变

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

并且不是

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

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

提前感谢您的任何建议。

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

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

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

    如果 /news/subfolder/ 中存在 file.html,这会将 /news/file.html 重写为 /news/subfolder/file.html /strong> .

    如果您的 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] 
    

    【讨论】:

    • 您好,感谢您的帮助。我尝试了您的代码,但仍然没有运气:即使 /news/subfolder/file.html 中的文件存在,url /news/file.html 也会给出 404。我开始认为服务器变量有问题,因为如果我转到 /news/subfolder/news1.html 代码 %{DOCUMENT_ROOT}/news/subfolder/$1.html 变成 C:/xampp/htdocs/新闻/子文件夹/新闻/子文件夹/file.html
    • 是的,这就是某些服务器上的问题。我将为您发布一个可行的解决方案。
    • 你做到了!现在可以了,非常感谢!!还有一个小问题:是否也可以将 /news/subfolder/xxx.html 重定向到 /news/xxx.html?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2014-02-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多