如果文件夹不存在,Apache .htaccess 重定向

发布于 2025-01-03 19:56:59 字数 629 浏览 3 评论 0 原文

我需要执行以下操作

我有一个网站,如果 http://example.com/user1 不存在, ,将用户重定向到 http://user1.example.com

类似地 http://www.example.com/user2 应重定向到 http://user2 .example.com

使用 .htaccess 文件可以实现这一点吗?

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) http://%{HTTP_HOST} [R]

上面重定向到主页,但是如何读取 / 后面的 URL 并进行上面的重定向呢?

I have a website where I need to do the following

if http://example.com/user1 does not exist, redirect the user to http://user1.example.com

Similarly http://www.example.com/user2 should redirect to http://user2.example.com

Is this possible using an .htaccess file?

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) http://%{HTTP_HOST} [R]

The above redirects to the home page, but how do I read the URL after / and do the redirect as above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看春风乍起 2025-01-10 19:56:59
RewriteCond %{SERVER_NAME} =example.com      # prevent infinite redirection
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteRule .* http://%1.%{SERVER_NAME} [R]

REQUEST_URI 上有点麻烦的正则表达式确保只有 http://example.com/user1 方案的 URL 才会被重定向(而不是 /user1/foo /栏)。

请注意使用SERVER_NAME而不是HTTP_HOST(后者是邪恶的,应该避免)。

RewriteCond %{SERVER_NAME} =example.com      # prevent infinite redirection
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteRule .* http://%1.%{SERVER_NAME} [R]

The somewhat cumbersome regex on REQUEST_URI ensures, only URLs of the http://example.com/user1 scheme will be redirected (as opposed to /user1/foo/bar).

Note the use of SERVER_NAME instead of HTTP_HOST (the latter is evil and should be avoided).

妄司 2025-01-10 19:56:59

尝试将以下内容添加到 example.com 网站根目录中的 .htaccess 文件中。

RewriteEngine on 
RewriteBase / 

#if on example.com host
RewriteCond %{HTTP_HOST} ^example\.com$ [NC] 
#and the directory/folder does not exist
RewriteCond %{REQUEST_FILENAME} !-d
#redirect to folder.example.com
RewriteRule ^(\w+)$ http://$1.%{HTTP_HOST} [R,L]

Try adding the following to the .htaccess file in the root directory of your example.com site.

RewriteEngine on 
RewriteBase / 

#if on example.com host
RewriteCond %{HTTP_HOST} ^example\.com$ [NC] 
#and the directory/folder does not exist
RewriteCond %{REQUEST_FILENAME} !-d
#redirect to folder.example.com
RewriteRule ^(\w+)$ http://$1.%{HTTP_HOST} [R,L]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文