简体   繁体   中英

Page Title in URL with .htaccess and Php

I have been smashing my head against wall for whole day but could not understand how can I make my URL show the page title in URL instead of all query parameters.

I just simply wants to convert my this URL

http://www.def.com/post.php?id=1

to

http://www.def.com/my-page-title.html

I read many articles and specially questions on SO but non of them were really answering this. I do not have enough reputations to put other similar links here.

I just want to get the title of my page and show it in my URL.

A fairly standard .htaccess that will route all paths where a directory or file are not found at the path:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^route-page\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /route-page.php [L]
</IfModule>

Thereafter, you have to have the /route-page.php (whatever you name it) read the URI: $_SERVER['REQUEST_URI'], parse "/my-page-title.html" and figure out how to load the correct page from there.

route-page.php

<?php
    $path = $_SERVER['REQUEST_URI'];
    //query for row of data with that path...
    //output results

Because your actual page name may have symbols in it, it's best if you have the expected path "my-page-title.html" in an indexed column of your database. This way, you can quickly grab the page based on the path. Also, since all unfound URLs are going to this page, you need to handle 404 errors manually (ie if you don't find a page that matches the path specified, output a 404 error):

if( $pageNotFound ) {
    header("HTTP/1.0 404 Not Found");
    echo("<h1>Page Not Found</h1>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM