Search code examples
regexapache.htaccessmod-rewrite

Apache mod_rewrite from unfriendly query string to a friendly URL


I am new to regex and Apache mod_rewrite, I have tried several ways, it doesn’t convert to URL friendly, I don’t know what I’m doing wrong.

I want to convert from unfriendly query string to a friendly URL on these scenarios:

Scenario 1: From: https://example.com/page.php?page_url=life-is-good To: https://example.com/life-is-good/

My .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/$  /page.php?page_url=$1 [L,R=301]

Scenario 2: From: https://example.com/resources/?blog.php?blog_url=life-is-good To: https://example.com/blogs/life-is-good/

My .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(blogs)/(.*)/$ blogs/blog.php?blog_url=$2 [L,R=301]

Any help on this greatly appreciated.


Solution

  • Have it like this:

    RewriteEngine On
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+(blogs)/blog\.php\?blog_url=([^\s&]+) [NC]
    RewriteRule ^ /%1/%2/? [R=301,L,NE]
    
    RewriteCond %{THE_REQUEST} \s/+page\.php\?page_url=([^\s&]+) [NC]
    RewriteRule ^ /%1/? [R=301,L,NE]
    
    # ignore all the requests for existing files and directories
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    # internal forwards from pretty URL to actual one
    
    RewriteRule ^(blogs)/(.*)/$ $1/blog.php?blog_url=$2 [L,QSA,NC]
    
    RewriteRule ^(.*)/$ page.php?page_url=$1 [L,QSA]