.htaccess特定的URL到不同的端口

13

我想将一些URL重定向到不同的端口。我的 .htaccess 文件如下:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^(.*)/$
RewriteCond %{REQUEST_URI} !^(.*)(\.)(.*)$
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}/ [R=301,L]
我需要添加一条规则,将所有以^some-prefix/开头的请求重定向到8080端口,例如:

1- URL


1- URL

http://www.mysite.com/page1

将重定向到

http://www.mysite.com/page1/

但是

2- 网址(URL)

http://www.mysite.com/some-prefix/page2

将会重定向到

http://www.mysite.com:8080/some-prefix/page2/

我该怎么做?谢谢

1个回答

19

你可以用这种方式完成

RewriteEngine on

# redirect to 8080 if current port is not 8080 and "some-prefix/" is matched
RewriteRule ^some-prefix/(.*[^/])/?$ http://www.mysite.com:8080/some-prefix/$1/ [R=301,L]

# redirect with trailing slash if not an existing file and no trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ /$1/ [R=301,L]

编辑:考虑到您的评论,现在有新的代码。

RewriteEngine on

# redirect to 8080 if "some-prefix/" is matched
RewriteCond %{SERVER_PORT} !^8080$
RewriteRule ^some-prefix/(.*[^/])/?$ http://%{HTTP_HOST}:8080/some-prefix/$1/ [R=301,L]

# redirect with trailing slash if not an existing file and no trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ /$1/ [R=301,L]

1
嗨,谢谢。1-有没有一种方法可以仅应用端口规则,而不是已经是8080?2-我能避免明确设置域吗? - leticia
3
可以的。您可以看到我的编辑答案(我已经添加了新的代码)。 - Justin Iurman
如果您想重定向 /some-prefix,可以在第一条规则下添加以下内容:RewriteCond %{SERVER_PORT} !^8080$ RewriteRule ^some-prefix$ http://%{HTTP_HOST}:8080/some-prefix [R=301,L] - torkleyy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接