URL短链服务重定向规则技术咨询:将子路径URL重定向至带GET参数的目标URL
Hey there, let's break down why your current .htaccess configs aren't working and fix them step by step.
Why your first config didn't work
Your initial rule RewriteRule ^/(.*)$ index.php?p=$1 [R=301,L] failed because in .htaccess files, the RewriteRule pattern doesn't include the leading slash. Apache strips the leading slash when processing requests in .htaccess, so ^/(.*)$ never matches any incoming request. That's why no redirect happened at all.
Why you got the too-many-redirects error
When you removed the leading slash, your rule became RewriteRule ^(.*)$ index.php?p=$1 [R=301,L] — but this matches every single request, including the index.php file itself. Here's the loop:
- You visit
http://www.shortener/url→ rule redirects toindex.php?p=url - Now
index.phpis requested → rule matches again, redirects toindex.php?p=index.php - This repeats infinitely, triggering the
ERR_TOO_MANY_REDIRECTSerror.
The Correct .htaccess Config
We need to add conditions to exclude index.php (or existing files/directories) from the rewrite rule to prevent loops. Here are two solid options:
Option 1: Explicitly exclude index.php
This targets only requests that aren't for index.php itself:
RewriteEngine On # Don't apply the rule to index.php RewriteCond %{REQUEST_URI} !^/index\.php$ # Rewrite any other path to index.php with the path as the 'p' parameter RewriteRule ^(.*)$ index.php?p=$1 [L]
Option 2: Exclude all existing files and directories
This is more flexible if you plan to add static files (like CSS, images) later — it only rewrites requests that don't point to a real file or folder:
RewriteEngine On # Skip if the request is for an existing file RewriteCond %{REQUEST_FILENAME} !-f # Skip if the request is for an existing directory RewriteCond %{REQUEST_FILENAME} !-d # Rewrite to index.php with the path as the 'p' parameter RewriteRule ^(.*)$ index.php?p=$1 [L]
A quick note on [R=301]
I removed the [R=301] flag because it triggers an external redirect (your users would see index.php?p=url in their address bar). For a URL shortener, you almost always want an internal rewrite (the address bar stays as http://www.shortener/url while the server serves index.php). If you specifically need an external redirect, add [R=301,L] back, but make sure the conditions still exclude index.php to avoid loops.
Final Checks
- Make sure your .htaccess file is in the root directory of your OVH hosting (where index.php is located).
- OVH typically allows .htaccess by default, but if you still have issues, confirm that the
AllowOverride Alldirective is set for your site in Apache's config (you might need to reach out to OVH support if you don't have access to the main Apache config).
内容的提问来源于stack exchange,提问作者Julien Sullivan

