skip to Main Content

This is my url:

http://localhost/blog/post/?meta=How-We-Build-Your-Website

and I need it to be like this:

http://localhost/blog/How-We-Build-Your-Website

How can I do it with .htaccess?

2

Answers


  1. I’m pretty sure the only way to do this would be by redirecting it in PHP.

    You can do this by editing the post.php file, and putting this at the top of the file:

    <?php if (isset($_GET['meta'])) { header("Location: ../".$_GET['meta']); exit; } ?>
    

    This redirects to to the page without loading any other page data. If there is no "?meta=…" though, it will not redirect, it will instead load the rest of the page.

    Login or Signup to reply.
  2. To internally rewrite a request for the friendly URL /blog/How-We-Build-Your-Website to /blog/post/index.php?meta=How-We-Build-Your-Website (the underlying file that actually handles the request) you can do something like the following in .htaccess using mod_rewrite:

    RewriteEngine On
    
    RewriteRule ^blog/([^w-]+)$ blog/post/index.php?meta=$1 [QSA,L]
    

    The subpattern ([^w-]+) captures the part of the URL-path after /blog/ and stores this in the $1 backreference, which is used later as the meta URL parameter value in the substitution string (2nd argument). The regex character class [^w-] matches characters in the range a-z, A-Z, 0-9, _ (underscore) and - (hyphen), which covers your example.

    The QSA flag will also append any query string that was on the initial request. If you are not expecting a query string on the initial request then you should remove this flag.

    To clarify, you still need to actually change the URL in your HTML source to the canonical/friendly URL. ie. /blog/How-We-Build-Your-Website.

    Note that if you have other directives in .htaccess then the order can be important.

    Reference:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search