简体   繁体   中英

PHP auto create seo friendly url

I have PHP url for show content for each page in language like :

category:

articles
gallery
page
books
....

URL:

http://localhost/cms/load.php?page=articles&id=1&title=this-is-a-title.html&lang=ru
http://localhost/cms/load.php?page=page&id=10&title=this-is-a-page-title.html&lang=ru

In action i need to auto rewrite url to seo friendly url like this :

http://localhost/cms/ru/articles/1/this-is-a-title.html
http://localhost/cms/ru/page/10/this-is-a-page-title.html

load.php

$page = isset($_GET['page']) ? safeGET($_GET['page']) : null;
$id   = isset($_GET['id'])   ? safeGET($_GET['id'])   : null;
if ($page=='articles') { include 'article.php'; } elseif { ... }

how do can i generate this URL with PHP (Preference without mod-rewrite)?! OR with .htaccess and PHP ?

You can achieve this in the following way:

.htaccess

RewriteEngine on
RewriteBase /cms/
RewriteRule ^([a-z,A-Z]+)/([a-z,A-Z]+)/([0-9]+)/([a-z,A-Z,0-9]+)$ ./load.php?page=$2&id=$3&title=$4&lang=$1 [L,NC]

This way your load.php file doesn't need to change and can accept the seo urls.

You will need to change the code that creates your URLs, if you update your answer how your URL's are currently being generated we can help you with that too.

I'd recommend using a routing class. You'd add a htaccess file that rewrites everything to a index.php file, then you'd control all the routing within PHP.

AltoRouter is my favorite one https://github.com/dannyvankooten/AltoRouter . It's inspired by Ruby's Sinatra, but if you Google "PHP routing class" you can find many more similar classes to use for routing your urls.

save yourself some pain and use a routing framework (ie http://www.slimframework.com/ )

though creation of the seo friendly urls (also called slugs) is not included

Here you can find two useful guides i used to understand how .htacces works. There are a lot of good example, I hope it helps:

First guide: http://code.tutsplus.com/tutorials/the-ultimate-guide-to-htaccess-files--net-4757

Second guide: https://www.branded3.com/blog/htaccess-mod_rewrite-ultimate-guide/

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