0

I want to redirect any request that doesn't have the last segment contain a dot to .html

examples:

/travels/
/travels.html
/travels/categories/new-zealand
/travels/categories/main.js

Line 2 and 4 should not be redirected while line 1 and 3 should be redirected to:

/travels.html
/travels/categories/new-zealand.html

I already have this regex that seems to work for capturing: ^(https?:\/\/.+(\..+)*\/)?[^\s.]+$

How do I exactly make this redirect happen? I have a vserver with an apache werbserver that is running and mod_rewrite is enabled. How exactly would the rewrite statement look and where do I put it? If I put it in a .htaccess file, where do I keep that? Inside the root of the page or anywhere?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
ivsterr
  • 128
  • 1
  • 7
  • This answer to this qestion also works for my question: https://stackoverflow.com/a/62885271/5211055 – ivsterr Apr 04 '21 at 19:49

1 Answers1

1

You can not match against host and https header in the rule's pattern. You can only match against URL path in a RewriteRule . To check the host and https header you need to use RewriteConds

 RewriteEngine on
# URL scheme is HTTPS
 RewriteCond %{HTTPS} on
# Host is www.example.com or example.com
 RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
#URL path is /travels/ then redirect the request to /travels.html
 RewriteRule ^/?travels/$ /travels.html [R,L]

This will redirect https://example.com/travels/ to https://example.com/travels.html . This changes the URL in your browser from old to the new one, if you want the redirection to happen internally then just remove the R flag.

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • how can I make that last RewriteRule dynamically that it works for any URL? for example it should also turn `/foo/bar` into `/foo/bar.html` and `/foo` into `/foo.html` – ivsterr Apr 01 '21 at 14:27
  • @ivsterr Just replace the rule with `RewriteRule ^/?(travels|foobar|foobar2)/$ /$1.html [R,L]` – Amit Verma Apr 01 '21 at 14:35
  • But that is still not dynamic is it? I would have to add every page that I ever create – ivsterr Apr 01 '21 at 17:17
  • Also: do i place the .htaccess next to my index.html or where do I put it? I am trying to get it to work with`/travels` redirecting to `/travels.html` – ivsterr Apr 02 '21 at 17:10
  • @ivsterr yes this is not dynamic . You have to manually add other paths to it. You can also use a dynamic pattern like `^/?(.+)/$` but since it catches all requests it can conflict with your other rules and URIs if you use a dynamic one. – Amit Verma Apr 03 '21 at 06:48