Search code examples
apache.htaccessmod-rewriteurl-rewriting

I want to rewrite https://blog/home/post?read=example to https://blog/home/example with .htaccess


I have tried many methods but none has worked. Blog is the name of the domain, Home is a folder in the domain and post.php is the page getting details from database. So, in my domain, I have: home/post.php

RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests

Above is the last code I used and it is not working. I'm getting a 404 error.


Solution

  • RewriteEngine On    # Turn on the rewriting engine
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([A-Za-z0-9_-]+)$ /post?read=$1 [L]    # Handle page requests
    

    The .htaccess is located in the root of the folder.

    You seem to be ignoring the home subdirectory. (Although you've referred to both home and Home in your question - note that this is case-sensistive.) And if "/post is a PHP file" then you should presumably be rewriting to post.php, not simply post?

    Note that Apache does not support line-end comments, as you are using here. (At best they get ignored, at worst they trigger a 500 error.)

    If the .htaccess file is located in the document root, as you suggest then you would need to write the rule as follows:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^home/([\w-]+)$ home/post.php?read=$1 [L]
    

    The \w shorthand character class is the same as [A-Za-z0-9_].

    The RewriteRule pattern matches the URL-path relative to the location of the .htaccess file.

    If, on the other hand, the .htaccess file is in the /home subdirectory (ie. at /home/.htaccess) then you would write the rule like this instead:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w-]+)$ post.php?read=$1 [L]
    

    Note, there is no slash prefix on the substitution string.