【问题标题】:Redirecting from document root to folder with htaccess使用 htaccess 从文档根目录重定向到文件夹
【发布时间】:2019-04-30 19:09:03
【问题描述】:

我的目录结构是这样的,我的文档根是/

/
.htaccess
    /public

这一切都在我的本地 xampp 服务器上。 服务器设置为侦听 mydomain.local,并且在我的 hosts 文件中,我已将 mydomian.local 指向 localhost。

我正在使用以下 .htaccess 代码,当使用 mydomain.local 作为地址时它可以正常工作。

我遇到的问题是当我使用 localhost/mydomain 作为地址时它不起作用

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ public/index.php?path=$1 [NC,L,QSA]

当使用 localhost/mydomain 作为地址时,如何让它工作?

这是因为我正在尝试注册 service worker,但它们只能通过 https 或 localhost 工作。

提前致谢

【问题讨论】:

  • 你能在 url 重写中添加预期的行为吗?您的意思是 locahost/mydomain = mydomain.local 还是等待 localhost/public/index.php?path=mydomain 这将是您设置的逻辑结果。除此之外,您使用的是虚拟主机还是别名?
  • @Bertrand localhost/mydomain/page = mydomain.local/page = mydomain.local/index.php?path=page

标签: php .htaccess apache2


【解决方案1】:

您还可以通过更改您的重写规则以在匹配中添加可选的mydomain/ 但不使用它,从而将单个 .htaccess 文件保留在根目录:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Add optional group
RewriteRule ^(mydomain/)?(.*)$ /public/index.php?path=$2 [NC,L,QSA]
# Same with a non capturing group
RewriteRule ^(?:mydomain/)?(.*)$ /public/index.php?path=$1 [NC,L,QSA]

顺便说一句,你可以使用htaccess tester来检查规则重写对url的影响

【讨论】:

  • 组和非捕获组是什么意思?
  • 您定义一个带括号的捕获组,并可以将其用作替换值:第一个括号可用作 $1 等等。您可以通过在括号内容前添加 ?: 来避免捕获。通过执行 (*.) 您可以捕获任何内容,并且可以用作 $1(您的方式)。在我的示例中,我已经将两种方式都用于管理(mydomain/)第一组
【解决方案2】:

我修好了。

根文件夹.htaccess

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

公共文件夹 .htaccess

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?path=$1 [NC,L,QSA]

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 2021-09-03
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多