Laravel: Apache alias for URLs with trailing slash

巧了我就是萌 提交于 2021-02-08 05:31:11

问题


I have a Laravel website in directory /home/user/Documents/laravel-training.

I would like to visit my website from http://localhost/dev/,
so I set an alias in /etc/apache2/sites-enabled/000-default.conf.

Here is my 000-default.conf:

<VirtualHost *:80>
    ServerName foo.example.net

    ServerAdmin foo@example.org
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /dev /home/user/Documents/laravel-training/public
    <Directory /home/user/Documents/laravel-training/public/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

</VirtualHost>

I also added RewriteBase /dev to the beginning of /home/user/Documents/laravel-training/public/.htaccess.

Now, I can visit my website successfully in case the URL does not ends with a slash.

For example, if I add the following route:

Route::get('test', function() {
    return view('welcome');
});

Then I can visit it from http://localhost/dev/test.

But if my URL is http://localhost/dev/test/, the server will incorrectly redirect my page to http://localhost/test, and causes a 404 Not Found error.

Not Found
The requested URL /test was not found on this server.

Apache/2.4.12 (Ubuntu) Server at localhost Port 80

Does anyone know how to fix this problem?


In response to Stefano Ortisi's comment:
I did not change anything else in .htaccess. I just kept the default settings.

RewriteBase /dev

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

回答1:


It is not an error that it redirects without the trailing slash.

In your public/.htaccess as you can see there is the following lines:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

^^^ as the comment states that will redirect a url with a trailing slash if it is not a folder. If you remove that you will see it will not redirect you.



来源:https://stackoverflow.com/questions/35509546/laravel-apache-alias-for-urls-with-trailing-slash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!