【问题标题】:mod_rewrite /foo to /index.php?id=foo AND /foo/foo2 to /index.php?id=foo/foo2mod_rewrite /foo 到 /index.php?id=foo AND /foo/foo2 到 /index.php?id=foo/foo2
【发布时间】:2023-04-01 08:27:01
【问题描述】:

我对 mod_rewrite 有疑问。

我想重定向标题中的那些 URI。我使用以下规则

RewriteEngine on

RewriteCond $1 !^(folders not to be redirected e.g. css|images)
RewriteCond $1 !^(.*).(file extension e.g. png|css|txt|php)

RewriteRule ^(.*)$ index.php?id=$1 [L]

只有当我将所有资源都放在一个文件夹中时它才有效,否则它会告诉我:

"/foo/index.php" not found.

所以为了解决我把所有的资源都放在了“www”文件夹里

但是当我尝试从例如的子文件夹加载资源时“foo”告诉我:

The requested URL "/foo/foo2" was not found on this server.

如何从“/foo/foo2”甚至“/foo/foo2/foo3”之类的子文件夹加载资源?

以及如何解决自动搜索文件夹中 index.php 的问题?

【问题讨论】:

    标签: php .htaccess mod-rewrite subdirectory clean-urls


    【解决方案1】:

    我相信您可以使用以下方法来达到您想要的结果。它不按文件扩展名过滤,而是检查文件是否实际存在。有一点不同的是,它首先在您的链接后面附加一个斜杠,这是您可能不想要的。

    RewriteEngine on
    RewriteBase /
    
    # This appends a trailing slash. You will have to update http://so with your domain.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(.*)/$
    RewriteRule ^(.*)$ http://so/$1/ [L,R=301]
    
    # This does the internal redirect
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)/$ /index.php?id=$1 [L]
    

    如果你不想要尾斜线,你可以使用以下

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /index.php?id=$1 [L]
    

    【讨论】:

    • 你是对的。我不想在末尾附加那些丑陋的斜杠。但是如何删除它们或没有它们重写?
    • @JuliusRickert,我添加了另一个不带斜杠的选项。
    • 我认为不需要“[NC]”,但必须有“[L]”。我说的对吗?
    • [NC] 表示不区分大小写。 [L] 指的是如果为真则应用的最后一条规则。您可以添加[L,NC],但我不建议将其更改为[L]。我的第二个建议对你有用吗?如果是这样,请记住接受答案。
    • 我明天试试。是的,如果它有效,当然。 :) 一个问题:RewriteBase 是必需的吗? .htaccess 位于根文件夹中。
    猜你喜欢
    • 1970-01-01
    • 2014-11-21
    • 2020-07-02
    • 1970-01-01
    • 2011-11-14
    • 2023-03-17
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多