Chris
Chris

Reputation: 4411

Rewrite rule to direct to anchor on page (in context of other rewrite rules)

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.

Upvotes: 1

Views: 396

Answers (2)

anubhava
anubhava

Reputation: 785721

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]

Upvotes: 1

user10946716
user10946716

Reputation:

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]

Upvotes: 1

Related Questions