Search code examples
apache.htaccesstrailing-slash

Why does Apache throw a Forbidden error when using RewriteRule and going to an URL with a trailing slash at its end?


I want to build a search page for my application, and I am using .htaccess to make URLs look better. The search page is located at localhost/search. Furthermore, two optional parameters can be appended at the end of the URL, like this: localhost/search/post/12345. However, when no parameters are appended, only a trailing slash (localhost/search/), Apache throws a Forbidden error. I am not sure why this is happening as there is no folder named search on the server.

To better illustrate my problem, here are the links that work and the ones that don't are as follows:

Working:

  • localhost/search
  • localhost/search/post
  • localhost/search/post/
  • localhost/search/post/12345
  • localhost/search/post/12345/

Not working:

  • localhost/search/

search.php is located in the root directory along with the .htaccess file. So here is the .htaccess file:

RewriteEngine On

# Redirect HTTP traffic to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]

# Resolve .php file for extension-less php urls
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/.]+)$ $1.php [L]

# Search parameters
RewriteRule ^search?/?([0-9a-zA-Z_-]+)?/?([0-9a-zA-Z_-]+)?/?$ search.php?type=$1&data=&2

# 404 error
ErrorDocument 404 /errors/404.php

Solution

  • I figured out the problem, following this helpful answer on StackOverflow. In the .htaccess file, I changed the following lines:

    # Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/$ $1 [R=301,L]
    

    to:

    # Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/$ /$1 [L,R=301]