問題描述
如何使用 .htaccess 將動態 URL 更改為 SEO 友好 (how to change the dynamic URL to SEO friendly using .htaccess)
I want to change the dynamic URL www.example.com/business‑listing.php?id=7863
to www.example.com/some‑dynamic‑text/7863
.
Also I want to hide .php extension from all URL, for eg: the URL www.example.com/list/page.php
should be change to www.example.com/list/page
And also when an user enter the URL www.example.com/list/page.php
, he should restricted to access that page using that URL. Permit acess only using
www.example.com/list/page
I have tried the following .htaccess file:
DirectoryIndex home.php
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^home$ home.php
RewriteRule ^(.*)\.html$ $1.php [nc]
RewriteRule ^([a‑zA‑Z0‑9_,‑]+)/([a‑zA‑Z0‑9_,‑]+)$ business‑listing.php?id=$1
- This take the first regular expression as value of id, but I want the Second.
- This hide the php extension of only home.php, but I want all php files.
- This does not prevent the user when entering the URL with PHP extension, That is when an user enter the URL
www.example.com/bill/pay.php
the page is open, but I want to restrict it.
參考解法
方法 1:
Try this code:
RewriteRule ^$ ‑ [L]
RewriteCond $1 ^(*\.php)
RewriteRule ^(.*)$ ‑ [F,L]
RewriteRule ^/?([^\./]*)[:;,\.]*$ $1.php
RewriteRule ^list/(.*)$ business‑listing.php?id=$1
If you want the 'list' part of the URL dynamic, try:
RewriteRule ^(.*)/(.*)$ business‑listing.php?id=$2
方法 2:
RewriteRule ^(.*)/(.*)$ business‑listing.php?id=$2&second=$2 [R,NC,L]
Try this!
方法 3:
You should not do it using .htaccess. Migration to nginx will be very painful in this case. Also you should remember of Front Controller Pattern.
URL should be processed by PHP(python, ryby etc...). There is variety of ready frameworks for url routing and a lot of cool things, like database api or template engine. In the php‑world there are a lot of variants.As for me, I prefer Silex microframework and Symfony2. Yii and Zend2 are worth seeing too.
For example, in silex you can bind a function to url‑pattern in such a nice way:
// web/index.php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app‑>get('/hello/{name}', function ($name) use ($app) {
return 'Hello '.$app‑>escape($name);
});
$app‑>run();
Good luck.
(by HYDER ALI、Pieter、premananth、Alexey Sidash)