简体   繁体   中英

URL rewrite breaks relative paths

I recently spent days trying to get my .htaccess to rewrite URLs, of which I eventually prevailed. My typical URL is now rewritten from http://example.co.uk/pages/aboutMe/pages/aboutMe.php (don't ask) to http://example.co.uk/aboutMe , which I am very satisfied with.

But, as a result, my relative paths no longer work - I can no longer simply type ../images/email.png in the source code. Instead, I have to type the path in full - /pages/contact/images/email.png , which isn't good practise/convention, is very rigid (in that it's not flexible) and I can see this becoming very problematic in the future, if I ever decide to rename a folder, for example.

I realise that this is probably because it is referencing the current URL (not the original, unaltered one) and is getting confused as it is looking for a directory that doesn't exist. Is there a workaround for this? Or is this the price of having a neat URL?

Here are my RewriteRules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

# Remove www.
RewriteCond %{HTTP_HOST} ^www.mythofechelon.co.uk$ [NC]
RewriteRule ^(.*)$ http://mythofechelon.co.uk/$1 [R=301,L]

# Rewrite /pages/filename/pages/filename.php to /fileName
RewriteRule ^home/?$ /pages/index/pages/index.php [L]
RewriteRule ^projectsPortfolio/?$ pages/projectsPortfolio/pages/projectsPortfolio.php [L]
RewriteRule ^projectsPortfolio-flash/?$ pages/projectsPortfolio/pages/projectsPortfolio-flash.php [L]
RewriteRule ^projectsPortfolio-code/?$ pages/projectsPortfolio/pages/projectsPortfolio-code.php [L]
RewriteRule ^aboutMe/?$ pages/aboutMe/pages/aboutMe.php [L]
RewriteRule ^contact/?$ pages/contact/pages/contact.php [L]

I had to manually rewrite the URL for each of my pages as I was told there was no pattern in my URLs. Anyway, try not to get sidetracked by that.

As far as I know, there is no workaround for that. Depending your rewrite rules, you might be able to create another set of rewrite rules for the image folder (for instance, rewriting "http://example.co.uk/images" to "http://example.co.uk/pages/contact/images").

That being said, when you start rewriting URL, I really don't think it's a bad practice to use absolute path for the images. Actually it's more robust, as you can freely change the way the URL are rewritten without breaking every relative paths.

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