简体   繁体   中英

Getting PHP to read the clean URL created by .htacces

I'm trying to create clean URLs and so far I've managed to use .htaccess to convert the following URL:

www.example.com/index.php?catagory=Section1&page=Page1

into:

www.example.com/Section1/Page1/

The problem is then getting PHP to interpret the URL and extract the variables. Here's the code I'm using:

.htaccess code:

Options +FollowSymLinks
Options +Indexes
RewriteEngine on

INTERNAL STATIC URL TO DYNAMIC URL
RewriteRule ^/([^/]+)/?$ /index.php?c=$1 [L]
RewriteRule ^/([^/]+)/([^/]+)/?$ /index.php?c=$1&p=$2 [L]

EXTERNAL DYNAMIC URL TO STATIC URL
RewriteCond %{THE_REQUEST} ^[a-zA-Z0-9]{1,3}\ /index\.php\?catagory=([^&]+)\ HTTP/
RewriteRule ^index\.php$ http://www.example.com/%1/? [R=301,L] 
RewriteCond %{THE_REQUEST} ^[a-zA-Z0-9]{1,3}\ /index\.php\?catagroy=([^&]+)&page=([^&]+)\ HTTP/
RewriteRule ^index\.php$ http://www.example.com/%1/%2/? [R=301,L] 

PHP code:

$urlVariables = explode("/",$_SERVER['REQUEST_URI']);
$catagory = $urlVariables[1];
$page = $urlVariables[2];

With this I keep getting a 404 error page. If I add index.php into this line of the htacces code:

RewriteRule ^index\.php$ http://www.example.com/index.php/%1/? [R=301,L]

The page at least loads, but the css and images are not loaded.

When using mod_rewrite in a .htaccess file, you need to remove the contextual local path prefix from the pattern. So in case of the .htaccess file in the root directory the leading / :

RewriteRule ^([^/]+)/?$ /index.php?c=$1 [L]
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?c=$1&p=$2 [L]

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