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

JavaScript实现URL前缀匹配重定向(排除特定路径)求助

解决带排除规则的URL重定向问题

Got it, let's work through this redirect scenario you're dealing with. The goal is to redirect any request starting with /all-books/ (except the exact path /all-books/ itself) to the same URL without the /all-books/ prefix. Here's how to implement this correctly for both Apache and Nginx servers:

Apache (using .htaccess)

First, make sure mod_rewrite is enabled on your Apache server. Then add these rules to your .htaccess file in the root directory:

RewriteEngine On

# Skip redirect for the exact /all-books/ path
RewriteRule ^all-books/$ - [L]

# Redirect all /all-books/[something] to /[something]
RewriteRule ^all-books/(.*)$ /$1 [R=301,L]

Breakdown of the rules:

  • RewriteEngine On: Enables URL rewriting functionality.
  • The first rule (^all-books/$ - [L]): Explicitly matches the exact path /all-books/ and does nothing (-), with [L] telling Apache to stop processing further rules for this request.
  • The second rule (^all-books/(.*)$ /$1 [R=301,L]): Matches any path starting with /all-books/ followed by content, captures that content into $1, then redirects to /$1. R=301 sets a permanent redirect (use R=302 if you need a temporary one), and [L] stops further rule processing.

Nginx (server block configuration)

If you're using Nginx, add these rules to your site's server block configuration:

# Handle the exact /all-books/ path without redirecting
location = /all-books/ {
    # Add your default handling here (e.g., return 200; or point to your index file)
}

# Redirect all /all-books/[something] requests to /[something]
location ^~ /all-books/ {
    rewrite ^/all-books/(.*)$ /$1 permanent;
}

Breakdown of the rules:

  • location = /all-books/: The = operator creates an exact match for the path, so only requests to /all-books/ hit this block. You can leave it empty to use your server's default handling, or add specific logic here.
  • location ^~ /all-books/: The ^~ operator creates a prefix match with higher priority than regular expressions, ensuring this rule catches all other /all-books/-prefixed paths. The rewrite directive strips off the /all-books/ prefix, and permanent sets a 301 redirect (use redirect for 302).

Quick checks to ensure it works:

  • For Apache: Verify mod_rewrite is enabled (check via phpinfo() or your server control panel) and that your .htaccess file has proper read permissions.
  • For Nginx: After modifying the config, restart the service with sudo systemctl restart nginx (or equivalent for your OS).
  • Test both cases: Visit /all-books/ (should not redirect) and /all-books/bookTitle (should redirect to /bookTitle).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:27:39