How To Send All Requests To A CGI Script Without It Appearing In The URL From The .Htaccess File?

Viewed 121

I am trying to send all the requests to my web server to a .cgi script without it appearing in the url (The cgi script is running Python Flask)
For example, if you go to this url: https://example.com/page/page2
It would send the request to main.cgi with the path /page/page2, however /main.cgi wouldn't appear in the url. Also, I would like it so the user can not access any of the static files by going to their url.

So far, I have tried the following .htaccess files:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /main.cgi/$1 [L]

Sadly, this allows the user to access static files by going to their url. For example, the url example.com/static/image.jpg would return the image, not whatever is returned from the cgi script.

I have also tried:

RewriteCond %{REQUEST_URI} !=/main.cgi
RewriteRule .*/main.cgi

However, this removes the url path. For example, this url: example.com/hello would just be redirected to example.com.

How can I make the htaccess send requests to a cgi script without it appearing in the url?

1 Answers
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /main.cgi/$1 [L]

This rewrites all requests that do not map to real files (which includes directories) to /main.cgi, passing the requested URL-path as path-info to your script (which your CGI script is presumably expecting). I'm assuming this is working in that regard?

To rewrite everything then you would need to remove the RewriteCond directive (as you did later), but you do need to prevent internal requests for /main.cgi being internally rewritten, which would otherwise create a rewrite-loop (500 error response).

For example:

RewriteRule !^main\.cgi main.cgi%{REQUEST_URI} [L]

This rewrites all requests that are not already for /main.cgi to /main.cgi/<url>.

The ! prefix operator on the RewriteRule pattern negates the regex - to the rule is successful when the regex does not match. There is no slash prefix on the RewriteRule pattern when used in .htaccess. The slash prefix on the substitution string is not required here. The REQUEST_URI server variable contains the root-relative URL-path (including the slash prefix), so this does not need to be captured using the RewriteRule pattern.

RewriteCond %{REQUEST_URI} !=/main.cgi
RewriteRule .*/main.cgi

However, this removes the url path. For example, this url: example.com/hello would just be redirected to example.com.

These directives are not actually valid (the RewriteRule is missing a 2nd argument), so can't actually be doing anything? However, the RewriteRule pattern .*/main.cgi won't match the URL you stated earlier, so again, I can't see that this would be doing anything. (?)

Related