【问题标题】:Remove index.php from URL after query params without using .htaccess查询参数后从 URL 中删除 index.php,而不使用 .htaccess
【发布时间】:2020-09-02 05:57:28
【问题描述】:

我想在查询参数后从我的 URL 中删除 index.php

这是我的网址:

http://127.0.0.1/user/report?user=USERNAME

我已删除查询参数并使用以下方法将其转换为漂亮的 URL:

RewriteCond %{QUERY_STRING} !user=
RewriteRule ^([a-zA-Z0-9\-]+)/(.*)$ $2?user=$1 [L,QSA]
RewriteRule ^([a-zA-Z0-9\-]+)$ ?user=$1 [L,QSA]

现在,我的网址如下所示:

http://127.0.0.1/user/report/USERNAME

所以对这个 URL 的所有请求都将指向我项目的入口脚本,即web/index.php

当我使用以下路线获取数据时,它可以工作:

http://127.0.0.1/user/report/Default/index.php/api/registration/user-registrations/

但是当我从 URL 中删除 index.php 并像下面这样访问它时,它会抛出 404:

http://127.0.0.1/user/report/Default/api/registration/user-registrations/

Apache 配置文件:

Alias /user/report /path/to/project/web/
<Directory /path/to/project/web/>
    AllowOverride All
    Require all Granted
    RewriteOptions AllowNoSlash

    RewriteEngine On
    RewriteBase /user/report/
    RewriteOptions AllowNoSlash

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^[^.]+[^\/]$ $0\/ [R]

    RewriteCond %{QUERY_STRING} !user=
    RewriteRule ^([a-zA-Z0-9\-]+)/(.*)$ $2?user=$1 [L,QSA]
    RewriteRule ^([a-zA-Z0-9\-]+)$ ?user=$1 [L,QSA]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)\.(\d+)\.(bmp|css|cur|gif|ico|jpe?g|m?js|png|svgz?|webp|webmanifest|pdf)$ $1.$3 [L]
</Directory>

我正在使用 Symfony 路由我的所有路由。

【问题讨论】:

  • 您好 Akshay,您能分享可以重现此问题的最小 repo 吗?我想在本地玩一个有类似问题的项目。如果您有任何可以重现该问题的开源项目,您也可以分享它
  • 您是否更改了任何 apache conf 文件中的任何内容?我假设您只修改了项目中存在的 .htaccess 文件,对吧?
  • 不,我在项目中没有任何 .htaccess。我正在使用 apace site conf 进行重定向。

标签: php .htaccess symfony apache2 httpd.conf


【解决方案1】:

如果您使用的是 Apache 2.4,并且不想使用 .htaccess 文件(例如出于性能原因),则解决方案只是使用 oneliner:FallBackResource

你只需要这个:

<VirtualHost *:80>
    ServerName domain.tld
    ServerAlias www.domain.tld

    DocumentRoot /var/www/project/public
    DirectoryIndex /index.php

    <Directory /var/www/project/public>
        AllowOverride None
        Order Allow,Deny
        Allow from All

        FallbackResource /index.php
    </Directory>

    # optionally disable the fallback resource for the asset directories
    # which will allow Apache to return a 404 error when files are
    # not found instead of passing the request to Symfony
    <Directory /var/www/project/public/bundles>
        FallbackResource disabled
    </Directory>
</VirtualHost>

这甚至显示在Symfony's documentation

【讨论】:

  • 403 是“未授权”。你的 symfony 网站有什么安全措施吗?
  • 没有。我也给予了相应的权限。
  • 其实我用的是httpd。
  • “httpd”是什么意思? Httpd 是 Apache,仅此而已。您应该找出您的 apache 版本(运行 httpd -v),然后添加其余配置。
  • 它是 Apache/2.4.41。
猜你喜欢
  • 2013-01-01
  • 2021-10-02
  • 2015-01-20
  • 2023-03-07
  • 1970-01-01
  • 2011-05-20
  • 2017-03-15
  • 1970-01-01
相关资源
最近更新 更多