rewriting simple html files for SEO friendly URLS

2019-09-10 01:48发布

问题:

I have a simple file mydomain.com/business_nottingham.html and i want to re-write that to an SEO friendly URL, eg mydomain.com/business-nottingham/

I've googled all the examples but they seem to be designed for either CMSes or PHP scripts.

Is there a simple .htaccess re-write example available that allows me to do something very simple as above?

Edit: I managed to find the following code finally

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301] 

However, it's still not quite working. If i enter the tidy URL, i get re-directed to a 404 page, but putting in the exact .html file name gets me to the right file but doesnt present me with a clean url.

I've tried various combinations of the above by reading various articles and tutorials but for some reason it doesn't seem to work for me.

回答1:

You want to redirect only when the actual request is for an .html file, then you want to internally rewrite to the html file. The way URLs resolve is the browser shows where it thinks it's going (URL in the address bar), then the request is made to the web server. If the webserver (where the htaccess file is) wants to change what's in the browser's URL address bar, it needs to tell the browser to literally load an entirely different URL. The browser will then request the new URL. Then the server must internally rewrite that URL back to where the actual resource is (the first URL), but the browser doesn't see this happen.

RewriteEngine On

RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /([^\ ]+)\.html
RewriteRule ^ /%2/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.*?)/?$
RewriteCond %{DOCUMENT_ROOT}/%1.html -f
RewriteRule ^ /%1.html [L]