Search code examples
.htaccessmod-rewriteurl-rewriting

htaccess rewrite url: cannot find corresponding row in database anymore


I'm trying to rewrite my urls by replacing all spaces with a dash.

I got the following htaccess file so far:

RewriteEngine on

RewriteCond %{THE_REQUEST} (\s|%20)
RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI]
RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [R=301,DPI]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^archive/([^/]+)$ news?title=$1

RewriteRule ^cars/([^/]+)$ carbrands?brand=$1

Assume that the title of an article in my database is "This is a test". Then with my htaccess file, the url that will be generated is:

example.com/archive/This-Is-A-Test

But it cannot find the corresponding article in my database cause it's looking for the title "This-Is-A-Test" instead of "This Is A Test".

How can I solve this problem ?


Solution

  • Have your .htaccess like this:

    RewriteEngine on
    
    RewriteCond %{THE_REQUEST} (\s|%20)
    RewriteRule ^(\S+)(?:\s|%20)+(\S+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI]
    RewriteRule ^(\S+)(?:\s|%20)+(.*)$ /$1-$2 [R=301,DPI]
    
    RewriteRule ^archive/([^/]+)$ news?title=$1 [L,QSA]
    
    RewriteRule ^cars/([^/]+)$ carbrands?brand=$1 [L,QSA]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.*)$ $1.php [L]
    

    And inside your article.php add this line at the stop:

    $title = str_replace ('-', ' ', $_GET['title']);