403 forbidden error in custom module in magento - magento-1.9.1

I have custom module in magento, I am getting Forbidden error like below-
Forbidden
You don't have permission to access /index.php/custom/adminhtml_custom/save/id/73/key/46af940903ec3251359c2b5db00e8092/back/edit/ on this server.
This problem is coming after clicking on Save or save and continue edit button.
Here is the controller file which have save function--
<?php
class Assel_Custom_Adminhtml_CustomController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction() {
$this->loadLayout();
return $this;
}
public function indexAction() {
$this->_initAction()
->_addContent($this->getLayout()->createBlock('custom/adminhtml_custom'))
->renderLayout();
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('custom/custom')->load($id);
if ($model->getId() || $id == 0) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
Mage::register('custom_data', $model);
$this->loadLayout();
$this->_setActiveMenu('custom/items');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('custom/adminhtml_custom_edit'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('custom')->__('Item does not exist'));
$this->_redirect('adminhtml/cms_page/edit/',array('page_id' => $this->getRequest()->getParam('page_id')));
}
}
public function newAction() {
$this->_forward('edit');
}
public function saveAction()
{
$filedata = array();
$main_image = 'main_image';
$_helper = Mage::helper('custom');
if (!empty($_FILES[$main_image]['name'])) {
try {
$ext = $_helper->getFileExtension($_FILES[$main_image]['name']);
$fname = 'File-' . time() . $ext;
$uploader = new Varien_File_Uploader($main_image);
#$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;
$uploader->save($path, $_FILES[$main_image]['name']);
$filedata[$main_image] = 'assel/custom/' . $_FILES[$main_image]['name'];
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
$backgrounddata = array();
$background_image = 'background_image';
if (!empty($_FILES[$background_image]['name'])) {
try {
$ext = $_helper->getFileExtension($_FILES[$background_image]['name']);
$fname = 'File-' . time() . $ext;
$uploader = new Varien_File_Uploader($background_image);
#$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;
$uploader->save($path, $_FILES[$background_image]['name']);
$backgrounddata[$background_image] = 'assel/custom/' . $_FILES[$background_image]['name'];
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit',array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
$thumbdata = array();
$thumb_image = 'thumb_image';
if (!empty($_FILES[$thumb_image]['name'])) {
try {
$ext = $_helper->getFileExtension($_FILES[$thumb_image]['name']);
$fname = 'File-' . time() . $ext;
$uploader = new Varien_File_Uploader($thumb_image);
#$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;
$uploader->save($path, $_FILES[$thumb_image]['name']);
$thumbdata[$thumb_image] = 'assel/custom/' . $_FILES[$thumb_image]['name'];
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
$circleimagedata = array();
$circle_image = 'circle_image';
if (!empty($_FILES[$circle_image]['name'])) {
try {
$ext = $_helper->getFileExtension($_FILES[$circle_image]['name']);
$fname = 'File-' . time() . $ext;
$uploader = new Varien_File_Uploader($circle_image);
#$uploader->setAllowedExtensions(array("txt", "csv", "htm", "html", "xml", "css", "doc", "docx", "xls", "xlsx", "rtf", "ppt", "pdf", "swf", "flv", "avi", "wmv", "mov", "wav", "mp3", "jpg", "jpeg", "gif", "png","zip"));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;
$uploader->save($path, $_FILES[$circle_image]['name']);
$circleimagedata[$circle_image] = 'assel/custom/' . $_FILES[$circle_image]['name'];
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
$audiodata = array();
$audio_file = 'audio';
if (!empty($_FILES[$audio_file]['name'])) {
try {
$ext = $_helper->getFileExtension($_FILES[$audio_file]['name']);
$fname = 'File-' . time() . $ext;
$uploader = new Varien_File_Uploader($audio_file);
$uploader->setAllowedExtensions(array("wmv","mp3"));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'assel' . DS. 'custom' . DS;
$uploader->save($path, $_FILES[$audio_file]['name']);
$audiodata[$audio_file] = 'assel/custom/' . $_FILES[$audio_file]['name'];
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
if ($data = $this->getRequest()->getPost()) {
if (!empty($filedata[$main_image])) {
$data[$main_image] = $filedata[$main_image];
} else {
if (isset($data[$main_image]['delete']) && $data[$main_image]['delete'] == 1) {
if ($data[$main_image]['value'] != '')
$this->removeFile($data[$main_image]['value']);
$data[$main_image] = '';
}else {
unset($data[$main_image]);
}
}
if (!empty($backgrounddata[$background_image])) {
$data[$background_image] = $backgrounddata[$background_image];
} else {
if (isset($data[$background_image]['delete']) && $data[$background_image]['delete'] == 1) {
if ($data[$background_image]['value'] != '')
$this->removeFile($data[$background_image]['value']);
$data[$background_image] = '';
}else {
unset($data[$background_image]);
}
}
if (!empty($thumbdata[$thumb_image])) {
$data[$thumb_image] = $thumbdata[$thumb_image];
} else {
if (isset($data[$thumb_image]['delete']) && $data[$thumb_image]['delete'] == 1) {
if ($data[$thumb_image]['value'] != '')
$this->removeFile($data[$thumb_image]['value']);
$data[$thumb_image] = '';
}else {
unset($data[$thumb_image]);
}
}
if (!empty($circleimagedata[$circle_image])) {
$data[$circle_image] = $circleimagedata[$circle_image];
} else {
if (isset($data[$circle_image]['delete']) && $data[$circle_image]['delete'] == 1) {
if ($data[$circle_image]['value'] != '')
$this->removeFile($data[$circle_image]['value']);
$data[$circle_image] = '';
}else {
unset($data[$circle_image]);
}
}
if (!empty($audiodata[$audio_file])) {
$data[$audio_file] = $audiodata[$audio_file];
} else {
if (isset($data[$audio_file]['delete']) && $data[$audio_file]['delete'] == 1) {
if ($data[$audio_file]['value'] != '')
$this->removeFile($data[$audio_file]['value']);
$data[$audio_file] = '';
}else {
unset($data[$audio_file]);
}
}
if($data['block_type'] == 16)
{
$page_id=$this->getRequest()->getParam('page_id');
$url= Mage::helper('cms/page')->getPageUrl($page_id);
$char = Mage::getModel('character/character') -> getCollection();
$char->addFieldToFilter('name', $data['character']);
foreach($char as $character)
{
$id= $character->getData('id');
}
if($id)
{
$char = Mage::getModel('character/character')->load($id);
$char->setLink($url)->save();
}
}
foreach ($data as $key => $value) /* save configurable product id in array in database*/
{
if (is_array($value))
{
$data[$key] = implode(',',$this->getRequest()->getParam($key));
}
}
$model = Mage::getModel('custom/custom');
$model->setData($data)
->setId($this->getRequest()->getParam('id'));
try
{
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
//$data = $this->getRequest()->getPost();
$blockid=$this->getRequest()->getParam('id');
if(!isset($blockid) || $blockid=='') // check if it is a new block
{
if($data['sort']=='') //check if it contains 'sort' value
{
$resultArray1 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."'");
$totalRow=count($resultArray1);
$data['sort']=$resultArray1[$totalRow-1]['sort'];
$data['sort']=$data['sort']+1;
Mage::log('ashu11'.$data['sort']);
}
else
{
$resultArray2 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' and sort>='".$data['sort']."'");
if(count($resultArray2)>0)
{
foreach($resultArray2 as $result)
{
$write->query("update custom set sort ='".++$data['sort']."' where id='".$result['id']."'");
}
}
}
}
else
{
if($data['sort']=='') //check if it contains 'sort' value
{
$resultArray3 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND id='".$blockid."'");
$totalRow=count($resultArray3);
$data['sort']=$resultArray3[0]['sort'];
}
else
{
$resultArray4 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND id='".$blockid."'");
$sort1=$resultArray4[0]['sort'];
$sort2=$data['sort'];
if($sort2>$sort1)//downwoards
{
$resultArray5 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort >'".$sort1."' AND sort<='".$sort2."'");
foreach($resultArray5 as $result)
{
$write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'");
}
$write->query("update custom set sort ='".$sort2."' where id='".$blockid."'");
}
else
{
$resultArray7 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort<'".$sort1."' AND sort>='".$sort2."'");
foreach($resultArray7 as $result)
{
Mage::log($result['id']);
$write->query("update custom set sort ='".++$result['sort']."' where id='".$result['id']."'");
}
$resultArray6 = $read->fetchAll("select * from custom where page_id ='".$data['page_id']."' AND sort='".$sort2."'");
$write->query("update custom set sort ='".$sort1."' where id='".$blockid."'");
}
}
}
$model->setData($data)
->setId($this->getRequest()->getParam('id'));
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('custom')->__('Block was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $model->getId()));
return;
}
$this->_redirect('adminhtml/cms_page/index/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('custom')->__('Unable to find block to save'));
$this->_redirect('adminhtml/cms_page/index/');
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 && $this->getRequest()->getParam('page_id')) {
try {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sortTobeDelete=$read->fetchOne("select sort from custom where id='".$this->getRequest()->getParam('id')."'");
Mage::log($sortTobeDelete);
$resultArray = $read->fetchAll("select * from custom where page_id ='".$this->getRequest()->getParam('page_id')."' and sort >'".$sortTobeDelete."'");
Mage::log($resultArray);
if(count($resultArray)>0)
{
foreach($resultArray as $result)
{
$write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'");
}
}
$model = Mage::getModel('custom/custom');
$model->setId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('adminhtml/cms_page/index/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id'),'id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('adminhtml/cms_page/index/');
}
public function sortRowAction() {
$currentIndex=$this->getRequest()->getPost('curId');
$changedIndex=$this->getRequest()->getPost('chaId');
$rowId=$this->getRequest()->getPost('rId');
$pageId=$this->getRequest()->getPost('pageId');
$output['currentIndex'] = $currentIndex;
$output['changedIndex'] = $changedIndex;
$output['rowId'] = $rowId;
$output['pageId'] = $pageId;
$output['ashu'] = "sdfds";
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sort1=$currentIndex;
$sort2=$changedIndex;
try
{
if($sort2>$sort1)//downwoards
{
$resultArray5 = $read->fetchAll("select * from custom where page_id ='".$pageId."' AND sort >'".$sort1."' AND sort<='".$sort2."'");
foreach($resultArray5 as $result)
{
$write->query("update custom set sort ='".--$result['sort']."' where id='".$result['id']."'");
}
$write->query("update custom set sort ='".$sort2."' where id='".$rowId."'");
}
else
{
$resultArray7 = $read->fetchAll("select * from custom where page_id ='".$pageId."' AND sort<'".$sort1."' AND sort>='".$sort2."'");
foreach($resultArray7 as $result)
{
$write->query("update custom set sort ='".++$result['sort']."' where id='".$result['id']."'");
}
$write->query("update custom set sort ='".$sort2."' where id='".$rowId."'");
}
}catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
return;
}
$json = json_encode($output);
$this->getResponse()
->clearHeaders()
->setHeader('Content-Type', 'application/json')
->setBody($json);
}
public function removeFile($file) {
$_helper = Mage::helper('custom');
$file = $_helper->updateDirSepereator($file);
$directory = Mage::getBaseDir('media') . DS . $file;
$io = new Varien_Io_File();
$result = $io->rmdir($directory, true);
}
}
This code is running well on my localhost even on another server. but can't find out why it is nor working on its actual server.
.htacess--
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi
# Action php5-cgi /cgi-bin/php5-cgi
# AddHandler php5-cgi .php
############################################
## GoDaddy specific options
# Options -MultiViews
## you might also need to add this line to php.ini
## cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini
############################################
## this line is specific for 1and1 hosting
#AddType x-mapp-php5 .php
#AddHandler x-mapp-php5 .php
############################################
## default index file
DirectoryIndex index.php
<IfModule mod_php5.c>
############################################
## adjust memory limit
# php_value memory_limit 64M
php_value memory_limit 256M
php_value max_execution_time 18000
############################################
## disable magic quotes for php request vars
php_flag magic_quotes_gpc off
############################################
## disable automatic session start
## before autoload was initialized
php_flag session.auto_start off
############################################
## enable resulting html compression
#php_flag zlib.output_compression on
###########################################
# disable user agent verification to not break multiple image upload
php_flag suhosin.session.cryptua off
###########################################
# turn off compatibility with PHP4 when dealing with objects
php_flag zend.ze1_compatibility_mode Off
</IfModule>
<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
# Insert filter on all content
###SetOutputFilter DEFLATE
# Insert filter on selected content types only
#AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
# Netscape 4.x has some problems...
#BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
#BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
#BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
#SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
#Header append Vary User-Agent env=!dont-vary
</IfModule>
<IfModule mod_ssl.c>
############################################
## make HTTPS env vars available for CGI mode
SSLOptions StdEnvVars
</IfModule>
<IfModule mod_rewrite.c>
############################################
## enable rewrites
Options +FollowSymLinks
RewriteEngine on
############################################
## you can put here your magento root folder
## path relative to web root
#RewriteBase /magento/
############################################
## uncomment next line to enable light API calls processing
# RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]
############################################
## rewrite API2 calls to api.php (by now it is REST only)
RewriteRule ^api/rest api.php?type=rest [QSA,L]
############################################
## workaround for HTTP authorization
## in CGI environment
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
############################################
## redirect for mobile user agents
#RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
#RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
#RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]
############################################
## always send 404 on missing files in these folders
RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
############################################
## never rewrite for existing files, directories and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
############################################
## rewrite everything else to index.php
RewriteRule .* index.php [L]
</IfModule>
############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead
AddDefaultCharset Off
#AddDefaultCharset UTF-8
<IfModule mod_expires.c>
############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
ExpiresDefault "access plus 1 year"
</IfModule>
############################################
## By default allow all access
Order allow,deny
Allow from all
###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version
<Files RELEASE_NOTES.txt>
order allow,deny
deny from all
</Files>
############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags
#FileETag none
Can anyone help me pls to find out issue.

Related

Redirect HTTPS on multidomain Varnish

i have got two domain based on same framework (magento2)
domain1.it
domain2.com
I would like to redirect them to their respective SSL version.
https://domain1.it
https://domain2.com
Domain 1 is correctly configured to redirect to HTTPS and my varnish Config file is:
sub vcl_recv {
if ( (req.http.host ~ "^(?i)www.domain1.it" || req.http.host ~ "^(?i)domain1.it") && req.http.X-Forwarded-Proto !~ "(?i)https") {
return (synth(750, ""));
}
sub vcl_synth {
if (resp.status == 750) {
set resp.status = 301;
set resp.http.Location = "https://domain1.it" + req.url;
return(deliver);
}
the problem is the synth always redirect to the same domain.
I should add an if condition where i could call a subroutines that redirect to https for domain2
For the love of everything that is good, please stop using otherworldly status codes, 301 and 302 are perfectly fine, clearer and save you a line.
I would advise against using x-forwarded-proto and use an SSL/TLS terminator that supports the PROXY protocol, but since this is what you have, here you go:
sub vcl_recv {
if (req.http.X-Forwarded-Proto !~ "https") {
set req.http.location = "https://" + req.http.host + req.url;
return(synth(301));
}
}
sub vcl_synth {
if (resp.status == 301 || resp.status == 302) {
set resp.http.location = req.http.location;
return (deliver);
}
}
relevant link: https://info.varnish-software.com/blog/rewriting-urls-with-varnish-redirection
Bitnami Engineer here. I just reviewed the Varnish documentation and found this:
sub vcl_recv {
if (client.ip != "127.0.0.1" && std.port(server.ip) == 80 && req.http.host ~ "^(?i)example.com") {
set req.http.x-redir = "https://" + req.http.host + req.url;
return(synth(850, "Moved permanently"));
}
}
sub vcl_synth {
if (resp.status == 850) {
set resp.http.Location = req.http.x-redir;
set resp.status = 302;
return (deliver);
}
}
This is useful when you want to redirect the clients to an SSL-version of your site. More info here:
https://varnish-cache.org/trac/wiki/VCLExampleRedirectInVCL

Varnish not ignoring subdomain despite vcl rules

I am running a basic lamp server with apache on port 80, and varnish on port 81. I am attempting to exclude a subdomain of the primary site entirely, however I have had no luck in doing so thus far, and I'm not sure why.
As you can see below, I have a rule in place to A) skip logged in users on the subdomain, and B) skip the subdomain entirely. Neither of these seem to work however. Is there something wrong with my vcl configuration?
backend default {
.host = "my.server.ip.address";
.port = "80";
}
sub vcl_recv {
call identify_device;
# Allow the back-end to serve up stale content if it is responding slowly.
set req.grace = 2m;
# Always cache the following file types for all users.
if ( req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm)(\?[a-z0-9]+)?$" ) {
unset req.http.cookie;
}
# Don't serve cached pages to logged in users
if ( req.http.cookie ~ "wordpress_logged_in" || req.url ~ "vaultpress=true" ) {
return( pass );
}
#Lets skip the logged in users on subdomain too!
if ( req.http.cookie ~ "dmr_user" ) {
return (pass);
}
#skip subdomain.domain.com
if (req.http.host ~ "subdomain.domain.com") {
return (pass);
}
#Following for WooCommerce and comments
if (req.url ~ "^/(cart|my-account|checkout|addons|wp-comments-post)") {
return (pass);
}
#Lets skip the logged in users on entries too!
if ( req.http.cookie ~ "dmr_user" ) {
return (pass);
}
if ( req.url ~ "\?add-to-cart=" ) {
return (pass);
}
# Drop any cookies sent to WordPress.
if ( ! ( req.url ~ "wp-(login|admin)" ) ) {
unset req.http.cookie;
}
}
sub vcl_fetch {
if (beresp.ttl < 180s) {
set beresp.ttl = 180s;
}
if (!(req.url ~ "wp-(login|admin)")) {
unset beresp.http.set-cookie;
}
}
sub vcl_hash {
hash_data(req.http.X-Device);
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
} else {
set resp.http.X-Cache = "MISS";
}
}
You are only skipping the processing of the subdomain halfway into your handling, ie instructions are executed in order. Moving the skip domain check directly at the top of sub vcl_recv should ensure no other rules gets executed against requests to that subdomain.
Well guys, it turns out that what I needed was to use pipe instead of pass.
#skip subdomain.domain.com
if (req.http.host ~ "subdomain.domain.com") {
return (pass);
}
is now
#skip subdomain.domain.com
if (req.http.host ~ "subdomain.domain.com") {
return (pipe);
}
I also went ahead and moved it up to the top of the config. Altogether it works like a charm now. Thanks to everyone for their help!

How to exclude virtual host from varnish 3?

I want to exclude a single virtual host from varnish 3 config
Cache: [www].domain.tld
Dont Cache: host.domain.tld
### default.vcl
backend foo { .host = "domain.tld"; .port = "8880"; }
backend bar { .host = "host.domain.tld"; .port = "8880";}
# ...
if (req.url == "host.domain.tld") { set req.backend = bar; }
if (req.url == "host.domain.tld") { return(pass); }
if (req.http.Cookie && req.url == "host.domain.tld") { return(pass); }
# ...
### httpd.conf
Listen 8880
<VirtualHost vhost.domain.tld:8880>
DocumentRoot /var/www/foo/
ServerName vhost.doman.tld
</VirtualHost>
The request never reaches the virtual host. I guess the problem is that I request on port 80 and the host listens on port 8880.
What I can do to fix this?
req.url doesn't contain the domain. You want something like this instead:
sub vcl_recv {
if (req.http.host == "host.domain.tld") {
set req.backend = bar;
return (pass);
}
}
This will set the backend for any request going to the domain "host.domain.tld" to "bar" and pass directly to the backend (bypassing the cache).

gzip compression using varnish cache

Im trying to provide gzip compression using varnish cache. But when I set content-encoding as gzip using my below mentioned configuration for varnish (default.vcl). Browser failed to download those content for which i set content-encoding as gzipped.
Varnish configuration file:
backend default {
.host = "127.0.0.1";
.port = "9000";
}
backend socketIO {
.host = "127.0.0.1";
.port = "8083";
}
acl purge {
"127.0.0.1";
"192.168.15.0"/24;
}
sub vcl_fetch {
/* If the request is for pictures, javascript, css, etc */
if (req.url ~ "^/public/" || req.url ~ "\.js"){
unset req.http.cookie;
set beresp.http.Content-Encoding= "gzip";
set beresp.ttl = 86400s;
set beresp.http.Cache-Control = "public, max-age=3600";
/*set the expires time to response header*/
set beresp.http.expires=beresp.ttl;
/* marker for vcl_deliver to reset Age: */
set beresp.http.magicmarker = "1";
}
if (!beresp.cacheable) {
return (pass);
}
return (deliver);
}
sub vcl_deliver {
if (resp.http.magicmarker) {
/* Remove the magic marker */
unset resp.http.magicmarker;
/* By definition we have a fresh object */
set resp.http.age = "0";
}
if(obj.hits > 0) {
set resp.http.X-Varnish-Cache = "HIT";
}else {
set resp.http.X-Varnish-Cache = "MISS";
}
return (deliver);
}
sub vcl_recv {
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For ", " client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
req.request != "TRACE" &&
req.request != "OPTIONS" &&
req.request != "DELETE") {
/* Non-RFC2616 or CONNECT which is weird. */
return (pipe);
}
# Pass requests that are not GET or HEAD
if (req.request != "GET" && req.request != "HEAD") {
return(pass);
}
#pipe websocket connections directly to Node.js
if (req.http.Upgrade ~ "(?i)websocket") {
set req.backend = socketIO;
return (pipe);
}
# Properly handle different encoding types
if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|js|css)$") {
# No point in compressing these
remove req.http.Accept-Encoding;
} elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
} elsif (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";
} else {
# unkown algorithm
remove req.http.Accept-Encoding;
}
}
# allow PURGE from localhost and 192.168.15...
if (req.request == "PURGE") {
if (!client.ip ~ purge) {
error 405 "Not allowed.";
}
return (lookup);
}
return (lookup);
}
sub vcl_hit {
if (req.request == "PURGE") {
purge_url(req.url);
error 200 "Purged.";
}
}
sub vcl_miss {
if (req.request == "PURGE") {
purge_url(req.url);
error 200 "Purged.";
}
}
sub vcl_pipe {
if (req.http.upgrade) {
set bereq.http.upgrade = req.http.upgrade;
}
}
Response Header:
Cache-Control:public, max-age=3600
Connection:keep-alive
Content-Encoding:gzip
Content-Length:11520
Content-Type:application/javascript
Date:Fri, 06 Apr 2012 04:53:41 GMT
ETag:"1330493670000--987570445"
Last-Modified:Wed, 29 Feb 2012 05:34:30 GMT
Server:Play! Framework;1.2.x-localbuild;dev
Via:1.1 varnish
X-Varnish:118464579 118464571
X-Varnish-Cache:HIT
age:0
expires:86400.000
Any suggestion on how to fix it and how to provide gzip compression using varnish.
Varnish Cache 3.0 does most of the handling of Accept-Encoding automatically and you shouldn't mess with it.
Basically, if you want Varnish to compress an object just set beresp.do_gzip in vcl_fetch and it will compress it before storing it in cache. Uncompression happens automatically when needed.
The content-length seems to be wrong, try un-setting it. Also, why are you using the beresp instead of obj in vcl_fetch?
...
obj.http.Content-Encoding="gzip";
remove obj.http.Content-Length;
...
Check and see if you are with apache, and have mod_deflate enabled,
try disabling it.

How can I set gzip compression in zend framework website

I am new to zend. I have developed a website using zend framework. Now, I want to set gzip compression in my website. Would you please guide me step wise to implement this.
Thanks in advance.
kamal Arora
There are two methods to gzip output in your website.
Using Webserver.If your webserver is apache you can refer here for a good documentation on how to enable mod_deflate on your server.
Using zend framework. Try the following code which is from this website.
Create a gzip compressed string in your bootstrap file.
Code:
try {
$frontController = Zend_Controller_Front::getInstance();
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}
GZIP does not compress images, just the raw HTML/CSS/JS/XML/JSON code from the site being sent to the user.
I made for zend framework 2 (zf2) with your tip
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = str_replace(" ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));
if(#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
Honoring the answer of Bruno Pitteli, I think you can compress in the following way:
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[n".'1'."n//]]>"
);
$content = preg_replace($search, $replace, $content);
So the full code sample now looks like:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n".'1'."n//]]>"), $content);
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}