I'm trying to set an Environment variable if I got a specific HTTP Header sent.
So I tried a few different way that I will detail
Header set MY_HTTP_HEADER "1"
# tests with with SetEnvIf
SetEnvIf %{HTTP:MY_HTTP_HEADER} ^1$ THE_ENV=ok
SetEnvIf MY_HTTP_HEADER ^1$ THE_ENV=ok
SetEnvIf %{MY_HTTP_HEADER} ^1$ THE_ENV=ok
# tests with RewriteRule
RewriteCond %{HTTP:MY_HTTP_HEADER} ^1$
RewriteRule .* index.php [L,E=THE_ENV:ok]
RewriteCond MY_HTTP_HEADER ^1$
RewriteRule .* index.php [L,E=THE_ENV:ok]
There is something that I certainly missed, because all the codes above doesn't work.
EDIT
The correct one is SetEnvIf MY_HTTP_HEADER ^1$ THE_ENV=ok and like #anubhava pointed it doesn't work if you set the header in the same .htaccess so I created another page calling the actual page with CURL with this header curl_setopt($curl,CURLOPT_HTTPHEADER,array('MY_HTTP_HEADER: 1'));
You're making 2 mistakes:
1) This directive:
Header set MY_HTTP_HEADER "1"
Actually sends response header not request header. Use it like this to set request header:
RequestHeader set X-MY-HTTP-HEADER "1"
2) You're setting request header and checking for it in the same .htaccess. Try sending header in web request from browser (using some Rest client addon) and then you will find THE_ENV=ok env value in your index.php
Related
We are trying to solve language redirection "the right way" over at https://guestbell.com/. Some idioms first:
a) Each route has a starting URL parameter that identifies the language. e.g. https://guestbell.com/en for English and https://guestbell.com/es for Spanish. There are also https://guestbell.com/en/pricing etc.
b) You can also omit this parameter, e.g. https://guestbell.com/pricing . The language is then detected (cookie, browser-language, qs param or URL param) and added to the URL. Page is SPA in react, the detection is done by i18next library.
c) Every possible page is pre-rendered in HTML files that are served via static server.
Note that because the routes are pre-rendered, routes like https://guestbell.com/pricing doesn't in fact exist in the folder structure (because it's impossible to guess the language prior to front end detection)
What works so far:
You navigate to guestbell.com
You are redirected to https via htaccess
If the file is found, serve it.
If the file is not found, serve a PHP file that is written as follows:
<?php
$cookieName = "i18next";
$path = rtrim(strtok($_SERVER["REQUEST_URI"], '?'), '/');
$supportedLangs = [
'en',
'es',
];
$defaultLang = $supportedLangs[0];
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(isset($_COOKIE[$cookieName])) {
$lang = $_COOKIE[$cookieName];
}
$finalLang = $lang;
if (!in_array($lang, $supportedLangs)) {
$finalLang = $defaultLang;
}
$newPath = $finalLang . $path . '.html';
if (file_exists($newPath) || empty($path)) {
$newPath = $finalLang . $path;
header("Location: $newPath", true, 302);
} else {
$newPath = $finalLang . '/404';
header("Location: $newPath", true, 302);
}
?>
As you can see, it attempts to detect via cookie or browser language (we know that by this point, the URL param is not present)
This approach works fine but there is one issue.
When navigating to guestbell.com (as most people would), this results into 2 redirects:
HTTP => HTTPS
/ => /en
Ideally, I would like to eliminate this added overhead and do it in one redirect. The only way (that I can imagine at the moment) is to do it via htaccess. The issue is I have no idea if this is possible.
This is the current htaccess for completion sake:
ErrorDocument 404 /404.html
#This is extremely important as it disables rewriting route from en => en/ and then 403-ing on directory
#https://stackoverflow.com/questions/28171874/mod-rewrite-how-to-prioritize-files-over-folders
DirectorySlash Off
# BEGIN WWW omit
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ %{REQUEST_SCHEME}://%1%{REQUEST_URI} [R=301,L]
</IfModule>
# END WWW omit
# BEGIN HTTPS redirect
<IfModule BEGIN HTTPS redirectfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
</IfModule>
# END HTTPS redirect
# BEGIN Omit extension
<ifModule mod_rewrite.c>
#remove html file extension-e.g. https://example.com/file.html will become https://example.com/file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
</ifModule>
# END Omit extension
# BEGIN File detection
<ifModule mod_rewrite.c>
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.php - that file then takes care of language redirection
RewriteRule ^ /index.php
</ifModule>
# END File detection
# BEGIN Compress text files
<ifModule mod_deflate.c>
<filesMatch "\.(css|js|x?html?|php)$">
SetOutputFilter DEFLATE
</filesMatch>
</ifModule>
# END Compress text files
# BEGIN Cache
<ifModule mod_headers.c>
<filesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|svg|mp4)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
<filesMatch "\\.(css)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
<filesMatch "\\.(js)$">
Header set Cache-Control "max-age=31536000, private"
</filesMatch>
<filesMatch "\\.(xml|txt)$">
Header set Cache-Control "max-age=2592000, public, must-revalidate"
</filesMatch>
<filesMatch "\\.(html|htm|php)$">
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
</filesMatch>
<filesMatch "sw.js$">
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
</filesMatch>
</ifModule>
# END Cache
An alternative would be to leave the language detection to front-end in such cases, and thus losing the prerendering altogether. I don't like this too much as majority of people would navigate to root of the page instead of /en and therefore lose performance. But what worries me is that the performance will be lost anyways due to multiple redirect.
My question stands:
Is it possible to do cookie and browser-language redirection combined with HTTP => HTTPS inside htaccess? If so, could you provide any help in achieving such functionality? If not, could you share the best way of achieving this, or optionally verify that our approach using PHP is "good enough"?
Many thanks.
I want to redirect styles requests from subdomain to main domain
https://dir.example.com/assets/(.*) to https://example.com/assets/(.*)
I am able to successful manage this issue with subfolder via bellow code:
example.com/dir/assets/(.*) to example.com/assets/(.*)
RedirectMatch 301 ^/dir/assets/(.*)$ /assets/$1
I tried to modify for subdomain but bellow code is not working:
RedirectMatch 301 ^dir.example.com/assets/(.*)$ example.com/assets/$1
what will be correct way of rewriting assets from sub-domain to main domain ?
I did it:
RewriteCond %{HTTP_HOST} ^(.*)\.example\.org[NC]
RewriteRule ^/?assets/(.*)$ https://example.org/crm/assets/$1 [L,R]
but now i have bigger issue:
Access to font at 'https://example.org/crm/assets/plugins/roboto/fonts/Regular/Roboto-Regular.ttf?v=1.1.0' from origin 'https://crm1.example.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Edit
Found Solution for second issue
.htaccess
<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
Hi I've got a wierd issue after a htaccess url rewrite... it works fine for the homepage but if i use the format subdomain.domain.com some fonts don't work, some do. The icons don't work it just shows a placeholder icon. It can't load the woff files etc. I think it may be the htaccess directoryindex disabled but i've put a special rule to allow the homepage to be displayed. How do I do the same for the \img\font\ folder which has the fonts. Also more importantly is disabling directoryindex best practice (i did this to avoid index.html being appended to the url's otherwise the rewrite subdomains doesn't work as it always encounters trailing index.html. Is there a way to set directoryindex to empty "" so that the second query works and I don't have to keep adding rules to allow specific folders?
DirectoryIndex disabled
#rewrite homepage to index.php to allow homepage as directoryindex is disabled
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^/?$ index.php [L]
#Rewrite subdomains
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP_HOST} ^(^.*)\.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/index.php?sub=%1 [P,NC,QSA,L]
Thanks!
P.S The earth really is flat.
I'm getting CORS errors in the console but it's the files are on the same server and domain.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/img/icon/fonts/materialdesignicons-webfont.woff2?v=2.0.46. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). (unknown)
downloadable font: download failed (font-family: "Material Design Icons" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed source: http://example.com/img/icon/fonts/materialdesignicons-webfont.woff2?v=2.0.46
Adding this to htaccess fixed everything
<IfModule mod_headers.c>
#allow corrs access from subdomains
SetEnvIf Origin ^(https?://(?:.+\.)?example\.com(?::\d{1,5})?)$ CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin %{CORS_ALLOW_ORIGIN}e env=CORS_ALLOW_ORIGIN
Header merge Vary "Origin"
</IfModule>
On my development server running xampp on windows my .htacess rewrite rules are working fine. Once we went to our live server which is running Linux core 3.8.0-21-generic #32-Ubuntu SMP Server version: Apache/2.2.22 (Ubuntu), our rules which do not contain parameters no longer work, yet rules which do have parameters are working.
Options -Indexes
<filesMatch "\.(html|htm|txt|js|htaccess)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
ErrorDocument 404 /404.php
RewriteEngine On
#Main site rules
RewriteRule ^login/?$ login.php [NC,L]
RewriteRule ^contact/?$ contact.php [NC,L]
The above rules which go to contact.php and login.php do not work. But, this more complicated rule with parameters is working:
RewriteRule ^game/([a-zA-Z0-9]+)/?$ handles/handle-game-select.php?name=$1 [NC,L]
Is there differences between the two server environments which is causing this to occur?
Also, it appears that if we do something strange such as: RewriteRule ^contact.x contact.php [NC,L] we are able to reach contact.php...
Very confused on this one.
Thank you for any help.
I suspect that is due to enabling of MultiViews option. Add this line on top to disable it:
Options -MultiViews
Option MultiViews is used by Apache's content negotiation module that runs before mod_rewrite and and makes Apache server match extensions of files. So /file can be in URL but it will serve /file.php.
If I want to set an environment variable before RewriteRules are evaluated, I have to use SetEnvIf instead of SetEnv. However, SetEnvIf requires one to have a condition. As it is, I have:
SetEnvIf Request_Method ^ ENV=VALUE
Is there a better way to do this?
You can use mod_rewrite's E flag:
RewriteRule ^ - [E=ENV:VALUE]
Which will guarantee that it gets set before (or after) rules get applied.
Using SetEnvIf you can do something like:
SetEnvIf ENV ^(.*)$ ENV=VALUE