基于Flask的网站URL缩短及.htaccess配置问题(Namecheap共享服务器)
Hey there! Let's get that URL shortening sorted for your Flask app hosted on Namecheap. First, let's break down the issue with your current .htaccess config, then fix it up properly.
What's wrong with your current setup?
Your existing RewriteRule uses a server filesystem absolute path (/home/user/public_html/cgi-bin/app/app.cgi/$1), but in .htaccess files, rewrite targets should use paths relative to your website root (not the server's full file path). That's why your short URLs aren't working as expected.
Fixed .htaccess Configuration
Replace your current code with this:
RewriteEngine On # Skip requests for real files/directories (like CSS, JS, images) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Forward all other requests to your Flask CGI script, preserving the path RewriteRule ^(.*)$ /cgi-bin/app/app.cgi/$1 [L]
Key Details Explained
- Path Correction: We switched to a root-relative path (
/cgi-bin/app/app.cgi/$1) which is the correct format for accessing CGI scripts on Namecheap's shared hosting. - Static Resource Protection: The two
RewriteCondlines ensure real files (likestyle.css) and folders aren't sent to your Flask app, so your static assets load normally. - Path Preservation: The
$1captures the original request path (e.g.,contact) and passes it to your Flask CGI script, so your Flask routes (like/contact) will match correctly.
Quick Checks to Ensure It Works
- Double-check your Flask routes are defined correctly, for example:
@app.route('/contact') def contact_page(): return "Welcome to the Contact Page!" - Confirm Namecheap has
mod_rewriteenabled (most shared hosts have this on by default; if not, reach out to their support). - Make sure your
.htaccessis in your website's root folder (public_html) and has proper permissions (usually644).
Once you update the config, visiting mywebsite.com/contact will load your Flask route directly, with the clean short URL showing in the browser—no more messy cgi-bin path in sight!
内容的提问来源于stack exchange,提问作者Benjamin Okkema




