Pretty URLs with htaccess [duplicate]

2019-08-12 06:07发布

Possible Duplicate:
htaccess rewrite breaks relative paths

I am hoping someone can help me. I am trying to set my website to use pretty URLs.

I currently have a few htaccess commands which hide my subdomain folder containing all my php files as well as a command to change my protocol from http to https and vice versa. The pretty url is proving to be difficult. I want to do it solely by htaccess and not php. I managed to write a command which worked but non of my css or javascript worked after that.

# Redirect from website.com to www.website.com
RewriteCond %{HTTP_HOST} ^website.com [NC]
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# redirect url to www
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /defaultfolder/([^\ ]+)\ HTTP/
RewriteRule ^(.*)$ defaultfolder/error.php [L]

#this section hides the defaultfolder, tried to modify this code here to make friendly urls.
RewriteCond %{HTTP_HOST} www.website.com
RewriteCond %{REQUEST_URI} !defaultfolder/
RewriteCond %{REQUEST_URI} !images/
RewriteRule ^(.*)\/$ defaultfolder/$1\.php [L]

#https redirect
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} (/defaultfolder/)(login|securepages|pages)\.php
RewriteRule ^defaultfolder/(.*)$ https://www.website.com/$1 [R,L]

#http redirect
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} (/defaultfolder/)(index|nonsecure pages)\.php
RewriteRule  ^defaultfolder/(.*)$ http://www.website.com/$1 [R,L]

1条回答
爷、活的狠高调
2楼-- · 2019-08-12 06:53

non of my css or javascript worked after that.

This is probably a relative/absolute path issue. When you change the path of the URL, relative links are going to break because the base has changed. You can either add a couple of rules to point requests for css/js to the right places, or try adding the correct base using the <base> tag in the header of your pages. Something like:

<base href="/">

Otherwise you may have to rewrite the way css and js get resolved. Say for instance, you have all of your styles in /css/ and all your scripts in /js/:

RewriteCond %{REQUEST_URI} !^/css/
RewriteRule ^(.*\.css)$ /css/$1 [L]

RewriteCond %{REQUEST_URI} !^/js/
RewriteRule ^(.*\.js)$ /js/$1 [L]

<head><link rel="stylesheet" type="text/css" href="css/main.css" media="all"/>

and this is in the main subfolder

So that would mean you need a rule like this:

RewriteCond %{REQUEST_URI} !/defaultfolder/
RewriteRule ^(css|js)/(.*)\.(css|js)$ defaultfolder/%1/%2.%3 [L]
查看更多
登录 后发表回答