php to htaccess rewrite - redirect if no $_POST data
-
22-07-2019 - |
Question
if( count( $_POST ) < 1 ) {
// determine if this was a secure request - we use a non standard HTTPS port so the SERVER_HTTPS_PORT define should always be used in place of 443
$protocol = $_SERVER['SERVER_PORT'] == SERVER_HTTPS_PORT ? 'https' : 'http';
header( "HTTP/1.0 301 Moved Permanently" );
header( "Status: 301" ); // this is for chrome compliance
header( "Location: $protocol://".CLIENT_DOMAIN."{$_SERVER['REQUEST_URI']}" );
session_write_close();
exit;
}
Can this functionality be rewritten with .htaccess rules?
Logic:
If not a POST request, redirect to equivalent page with whole query string by issuing 301 header and status, whilst maintaining protocol.
Solution
Try this:
RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{SERVER_PORT}s ^443(s)|.*
RewriteRule ^foo/bar$ http%1://www.example.com%{REQUEST_URI} [L,R=301]
Not you just need to replace 443
by your SERVER_HTTPS_PORT
value and www.example.com
by your CLIENT_DOMAIN
value.
OTHER TIPS
This should work for you (replace www.google.com
with your CLIENT_DOMAIN
).
RewriteEngine on
RewriteCond %{SERVER_PORT} ^80$
RewriteCond %{REQUEST_METHOD} !^POST$ [NC]
RewriteRule ^(.*)$ http://www.google.com/$1 [L,QSA,R=301]
RewriteCond %{SERVER_PORT} ^443$
RewriteCond %{REQUEST_METHOD} !^POST$ [NC]
RewriteRule ^(.*)$ https://www.google.com/$1 [L,QSA,R=301]
Lookink at the documentation of Apache's mod_rewrite, there might be a way, using %{REQUEST_METHOD}
in a RewriteCond
condition ; something like this might do the trick :
RewriteCond %{REQUEST_METHOD} !=POST
Followed, of course, by the needed RewriteRule
to redirect everything to the non-POST page.
I have no way of testing right now, so this might not be perfect, but something like this could maybe do the trick -- or, at least, guide you to the solution :
RewriteRule ^(.*)$ $1 [QSA,R=301,L]
The idea beeing to
- match everything
- redirect to what was matched
- keeping the Query String (QSA flag)
- and redirecting with a 301 code
- and stopping there