.htaccessmod-rewriteblogsfriendly-urlpretty-urls

.htaccess pretty url for blog


I need a help with blog which is in core php and want to create a pretty url using .htaccess

I have a folder called blog where there are two files.

index.php which is a blog page post.php which display a signle blog post

so what I want to achieve is that someone one visit

https://example.com/blog/

It display data from index.php

on the post.php I get data using url slug not using id, so if someone write

https://example.com/blog/my-blogpost-url-slug

It needs to call post.php which has logic to get url so it will be post.php?url=my-blogpost-url-slug will be converted to https://example.com/blog/my-blogpost-url-slug

Basically

https://example.com/blog/index.php should open like example.com/blog/ https://example.com/blog/post?url=mypost-url-slug should open like https://example.com/blog/mypost-url-slug

Following code I tried but it is not working...

All index.php is being redirected to post.php and also url parmater is getting value post.php instead slug url

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

RewriteRule ^([\S\s/+.]+)/?$ post.php?url=$1 [NC,L]

Solution

  • With your shown samples please try following .htaccess rules file.

    Make sure to:

    RewriteEngine ON
    ##Rules for redirecting FROM https://example.com/blog/index.php TO example.com/blog/
    RewriteCond %{THE_REQUEST} \s/(blog)/index\.php\s [NC]
    RewriteRule ^ /%1? [R=301]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^blog/?$ blog/index.php [NC,L]
    
    ##Rules for redirecting FROM https://example.com/blog/post?url=mypost-url-slug TO https://example.com/blog/mypost-url-slug
    RewriteCond %{THE_REQUEST} \s/(blog)/post\.php\?(\S+)\s [NC]
    RewriteRule ^ /%1/%2? [R=301]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^blog/([^/]*)?$ blog/post.php?url=$1 [NC,L]