You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

基于Flask的网站URL缩短及.htaccess配置问题(Namecheap共享服务器)

解决Flask URL缩短问题(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 RewriteCond lines ensure real files (like style.css) and folders aren't sent to your Flask app, so your static assets load normally.
  • Path Preservation: The $1 captures 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_rewrite enabled (most shared hosts have this on by default; if not, reach out to their support).
  • Make sure your .htaccess is in your website's root folder (public_html) and has proper permissions (usually 644).

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

火山引擎 最新活动