在查询参数后从 URL 中删除 index.php 而不使用 .htaccess

aks*_*shi 8 php .htaccess apache2 httpd.conf symfony

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

这是我的网址:

http://127.0.0.1/user/report?user=USERNAME
Run Code Online (Sandbox Code Playgroud)

我已经删除了查询参数并将其转换为漂亮的 URL:

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

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

http://127.0.0.1/user/report/USERNAME
Run Code Online (Sandbox Code Playgroud)

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

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

http://127.0.0.1/user/report/Default/index.php/api/registration/user-registrations/
Run Code Online (Sandbox Code Playgroud)

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

http://127.0.0.1/user/report/Default/api/registration/user-registrations/
Run Code Online (Sandbox Code Playgroud)

阿帕奇配置文件:

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>
Run Code Online (Sandbox Code Playgroud)

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

yiv*_*ivi 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>
Run Code Online (Sandbox Code Playgroud)

Symfony 的文档中甚至也显示了这一点。