简体   繁体   中英

Remove index.php from URL after query params without using .htaccess

I want to remove index.php from my URL after query params.

This is my URL:

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

I have removed query params and convert it into pretty URL using:

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

Now, my URL looks like this:

http://127.0.0.1/user/report/USERNAME

So all the requests to this URL will point to the entry script of my project ie web/index.php .

When I use below routes to get data, it works:

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

But when I remove index.php from URL and access it like below, it throws 404:

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

Apache config file:

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>

I am using Symfony for routing all my routes.

If you are using Apache 2.4, and do not want to to use .htaccess files (eg for performance reasons), the solution is simply to use a oneliner: FallBackResource .

You would only need this:

<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>

This is even shown in Symfony's documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM