简体   繁体   中英

Working with .HTaccess for url redirects and rewrites

For a while now, I've been looking into using .htaccess , to make my URLs on my website more user friendly.

Having looked through what seems to be endless streams of information on the internet, however, I can't seem to find a way to do the following things with a plain English explanation of how the commands work.

I was advised by the technical support team at my hosting provider to ask a professional web developer, so I thought here would be a good place to ask. If however it is on the wrong site, I apologise in advance.

I think having the code and the explanations will help those who wish to achieve similar results get there a lot quicker rather than scrabbling around and getting confused.

To clarify, since I have certain objectives, I wish to do the following in my .htaccess file:

  1. Remove the file extension (www.mydomain.com/file.html and www.mysubdomain.domain.com/file.html) to make the URL look like www.mydomain.com/file/.
  2. Make these rules also apply to .shtml extensions for the root and subdomain so that if I were to add any .shtml files in the sub directory they would be handled without any extra work.

I'd like to do this in as few lines as possible as well to make it easier for other people to migrate and use in their site.

Thanks in advance for any help, it is much appreciated.

To remove the file extensions html and shtml , you can use the following:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/$ $1.html [NC,L]

RewriteCond %{REQUEST_FILENAME}.shtml -f
RewriteRule ^(.*)/$ $1.shtml [NC,L]

These are the steps taken:

  1. First, turn on the Rewrite Engine for this request.
  2. Then check if <request_uri>.html or <request_uri>.html exists. If so, internally rewrite <request_uri>/ (with the forward slash at the end, as you have specified) to the existing file.

If you would like to make the trailing forward slash optional, you can change the expression from ^(.*)/$ to ^(.*)/?$ (addition of the question mark makes it optional).

Solutions for you

To remove extension use:

RewriteRule ^([^\.]+)$ $1.html [NC,L] 

To apply .shtml use:

RewriteRule ^([^\.]+)$ $1.shtml [NC,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