skip to Main Content

I have the following in my .htaccess file in my domain root.

Options +FollowSymlinks
RewriteEngine On

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

RewriteRule ^/services/(.+) /services#$1 [NE]

The first instructions force HTTPS and directs all requests to a PHP file (e.g. /services -> /services.php).

The last instruction is adapted from this answer, aiming to redirect path components after /services to an anchor on that page (e.g. /services/item -> /services#item). However, it does not work and yields a 404 error.

I thought it might be due to the other rules, but removing them did not help (and trying some variations did not help either, or made the server try to find /services/item.php for example.

How should I fix this? Do I need to put the rules in a different order? For clarity, I want to rewrite the URL, so that .php and # are not visible to the user.

2

Answers


  1. I modified your rules, check it:

        Options +FollowSymlinks
        RewriteEngine On
    
        RewriteRule ^services/(.*)$ /services#$1 [R=301,L]
    
        RewriteCond %{HTTPS} !=on
        RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^([^.]+)$ $1.php [NC,L]
    
    Login or Signup to reply.
  2. Converting my comments to answer to help out future visitors to easily find a quick solution.

    Options +FollowSymlinks -MultiViews
    RewriteEngine On
    
    # redirect to https
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # pass query parameter to a php file internally
    RewriteRule ^services/([w-]+)/?$ services.php?param=$1 [L,NC,QSA]
    
    # handle .php extension
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^.]+)/?$ $1.php [L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search