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=301sets a permanent redirect (useR=302if 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. Therewritedirective strips off the/all-books/prefix, andpermanentsets a 301 redirect (useredirectfor 302).
Quick checks to ensure it works:
- For Apache: Verify
mod_rewriteis enabled (check viaphpinfo()or your server control panel) and that your.htaccessfile 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
相关产品推荐
相关产品推荐

