开发者

.htaccess falling over on trailing slash

开发者 https://www.devze.com 2023-03-20 20:07 出处:网络
TL;DR How can I get .htaccess to rewrite http://domain.com/images to http://domain.com/images/ (i.e. add a trailing slash to URLs without one)? The URLs can be deeper than one level, for example http

TL;DR

How can I get .htaccess to rewrite http://domain.com/images to http://domain.com/images/ (i.e. add a trailing slash to URLs without one)? The URLs can be deeper than one level, for example http://domain.com/images/page/1.

More info

Say I have a URL like this:

http://jamwaffles2/wallpapers

This will redirect to this in the URL bar, with the rewrite rule working fine:

http://jamwaffles2/wallpapers/?page=wallpapers

However

http://jamwaffles2/wallpapers/ (note trailing slash)

Rewrites fine to

http://jamwaffles2/index.php?page=wallpapers (not visible to user)

With a nice http://jamwaffles2/wallpapers/ in the address bar.

The issue here is that when a trailing slash isn't given to the URL, the URL in the address bar changes to a not-so-pretty one. Can someone offer a solution to this?

Here's my .htaccess:

# turn rewriting on
RewriteEngine on

RedirectMatch permanent ^/$ http://jamwaffles2/home

Options +FollowSymLinks

RewriteRule ^([^/\.]+)/?$ /index.php?page=$1 [L,NC,QSA]
RewriteRule ^([^/\开发者_高级运维.]+)/([^/\.]+)/?$ /index.php?page=$1&var1=$2 [L,NC,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /index.php?page=$1&var1=$2&var2=$3 [L,NC,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /index.php?page=$1&var1=$2&var2=$3&var3=$4 [L,NC,QSA]

As a side note, there are more levels to the URL; the .htaccess should make that apparent (e.g. http://jamwaffles2/home/page/2).

EDIT

Curiously, this only happens on /wallpapers. If I type in http://jamwaffles2/home it works as expected, but won't work with http://jamwaffles2/wallpapers.


1) Try this directive: Options +FollowSymLinks -MultiViews -- depending on Apache config it can be the deal breaker.

2) Use this code (one of possible variants) to add trailing slash for NON-EXISTING resources ONLY:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*[^/])$ /$1/ [R=301,L]

It will redirect (301 Permanent Redirect) so URL will change in browser (e.g. example.com/hello => example.com/hello/).


If it still does not work (for whatever the reason may be) -- if you can edit Apache config files -- please enable rewrite debugging (RewriteLogLevel 9) and check the rewrite log to see why some URL failing correct rewrite. Every server can be configured differently, so the same rule may work a bit differently in your case.

0

精彩评论

暂无评论...
验证码 换一张
取 消