Search code examples
php.htaccessurl-rewritingcanonical-link

Page Source is still showing the original page name after HTACCESS rewrite and using $_SERVER['PHP_SELF']


I am using an htaccess rewrite to change the name of a page named cities.php to the linked city page when clicked. For example if the link of Aliso Viejo was clicked you would see:

aliso-viejo-slab-leak-detection.php

The rewrite section of my htaccess is as follows:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^$
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301]
    RewriteRule ^([a-z]+)-slab-leak-detection.php$ cities.php?city=$1&state=$2
    RewriteRule ^([a-z-]+)-slab-leak-detection.php$ cities.php?city=$1&state=$2
    RewriteRule ^(.*)\.html$ $1.php [L]
    ErrorDocument 404 /index.php

Now the rewrite works as intended. The problem is for the canonical link I am using:

    $_SERVER['PHP_SELF']

to echo the page url for indexing purposes. Instead of echoing the rewritten page name it is echoing the original cities.php name. Search engines are also indexing the pre rewritten page as well.

I am assuming I have the code in the wrong order or do not have it coded correctly to write silently instead of dynamically.

Bear in mind I am pretty unfamiliar with advanced httaccess coding and the code I have used is from changed information I have researched.

Any help is greatly appreciated.


Solution

  • I don't think the value of $_SERVER['PHP_SELF'] is affected by .htaccess rewrites, because it references the filesystem, not the URL.

    If you need to reference the URL, use $_SERVER['REQUEST_URI']

    EDIT

    Just found this related question/answer: Can PHP access the .htaccess rewrite name of a file. Regilero's comment on the selected answer makes a good point about escaping the value of $_SERVER['REQUEST_URI'] before outputting it:

    Beware that you should escape $_SERVER['REQUEST_URI'] before using to build HTML content, avoid users injection HTML/js in the url. Check stackoverflow.com/a/326331/550618 for details on SCRIPT_NAME vs REQUEST_URI