You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已实现HTTPS/WWW跳转,.htaccess无法添加尾部斜杠如何解决?

Fixing the Trailing Slash Redirect in Your .htaccess

Alright, let's get that trailing slash working for you! The issue is almost always about rule order or not accounting for actual files/directories (we don't want to slap a slash on things like style.css or a real folder that already has one). Here's the adjusted .htaccess setup that will handle all three of your requirements correctly:

# Enable mod_rewrite
RewriteEngine On

# 1. Add trailing slash to non-file, non-directory URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

# 2. Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 3. Redirect non-WWW to WWW
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Let's break down why this works:

  • Trailing slash first: We handle this rule before the HTTPS/WWW redirects so that we only do one clean redirect chain (instead of multiple confusing hops). The two RewriteCond lines make sure we don't add a slash to:

    • Real files (!-f = not a file)
    • Real directories (!-d = not a directory)
      The RewriteRule targets any URL that doesn't end with a slash and appends one, using [L,R=301] to mark it as a permanent redirect and stop processing further rules for that request.
  • HTTP → HTTPS next: Once the URL has the correct trailing slash, we force all traffic to HTTPS.

  • Non-WWW → WWW last: Finally, we redirect any non-WWW requests to the WWW version, using https:// directly since we've already secured the connection.

Quick tips for testing:

  • Clear your browser cache first—301 permanent redirects get cached heavily, so old rules might still be stuck.
  • Double-check that your server has mod_rewrite enabled (most shared hosts have this on by default, but you can confirm with your host if needed).
  • If you have existing custom rules, make sure these three blocks come before any other rewrite rules to avoid conflicts.

内容的提问来源于stack exchange,提问作者Cosmin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:23:22