Search code examples
phpapache.htaccessmod-rewriteovh

why a rewrite_rule works only when the folder exist?


The objective is to input an url like

https://www.mywebsite/expert/188/name-of-the-expert

and return it to the server in the form

expert.php?exp=188

Like if the user typed in https://www.mywebsite/expert.php?exp=188

WHAT DOES NOT WORK: simple rules like RewriteRule ^expert-([0-9]*)$ expert.php?exp=$1 [L,NC,QSA]

WHAT WORK I have the following rewrite_rule that works only when I physically create the folder expert/ in my tree, i.e. /www/expert/

# FRIENDLY URL FOR EXPERTS PROFILE
Rewriterule ^(.*)expert\/([0-9]*)(\/[a-z0-9\-\']*)?\/?$ expert.php?exp=$2 [L,NC,QSA]

Also, for this rule to work, I had to put the <base href="/"> in the page expert.php to avoid errors with all my linked resources:

Failed to load resource: the server responded with a status of 404 ()

The server is APACHE on a shared web hosting platform named OVH.

The full code of the issue:

<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymlinks
RewriteBase /

# FRIENDLY URL FOR EXPERTS PROFILE
Rewriterule ^(.*)expert\/([0-9]*)(\/[a-z0-9\-\']*)?\/?$ expert.php?exp=$2 [L,NC,QSA]
</IfModule>

Solution

  • Have it like this with MultiViews turned off:

    Options +FollowSymlinks -MultiViews
    RewriteEngine On
    RewriteBase /
    
    # FRIENDLY URL FOR EXPERTS PROFILE
    Rewriterule ^/?expert/(\d+)/?$ expert.php?exp=$1 [L,NC,QSA]
    

    Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.