Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e. 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.

like image 767
akshaypjoshi Avatar asked May 16 '20 10:05

akshaypjoshi


1 Answers

If you are using Apache 2.4, and do not want to to use .htaccess files (e.g. 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.

like image 181
yivi Avatar answered Sep 28 '22 01:09

yivi