skip to Main Content

I’ve developed my own CMS in PHP and now I’d like to make it SEO-Friendly, but I’m having some problems.

Most of the pages of the website are accessible from a id, like:

www.example.com/?id=alphanumericId123
www.example.com/?id=main

and so on, and I’d like to rewrite the URL of this pages:

www.example.com/aplhanumericId/
www.example.com/main/

I have wrote this rewrite rule, and it works fine:

RewriteEngine On
RewriteRule ^([^/d]+)/?$ index.php?id=$1 [QSA]

but It cannot work for those few pages that are accessible by a static file or just for the scripts.
Isn’t there a way to make some exceptions? Like:

if the requested file exsist {
    if it is protected {
        display error 403
    } else {
        display file
} } else {
    rewrite rule
}

2

Answers


  1. Use the following before your RewriteRule

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    Basically it checks if it’s not a file, and not a directory.

    Login or Signup to reply.
  2. You should not rewrite paths to existing files and directories:

    RewriteEngine On
    # Exclude existing files
    RewriteCond %{REQUEST_FILENAME} !-f
    # Exclude existing directories
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/d]+)/?$ index.php?id=$1 [QSA]
    

    Also note that your rule will not allow you alphanumeric id’s as you are excluding numbers.

    Alternatives would be:

    ...
    # No forward slash
    RewriteRule ^([^/]+)/?$ index.php?id=$1 [QSA]
    

    or

    ...
    # Only a selection of characters including - and _
    RewriteRule ^([-w]+)/?$ index.php?id=$1 [QSA]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search