I am trying to set up a varnish (4) server with 2 backends. However when I try to access it with 2 different URLs it always reverts to server1's backend. Here are the relevant parts of my .vcl file.
Backend server configuration:
backend server1 {
.host = "127.0.0.1";
.port = "83";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
}
backend server2 {
.host = "127.0.0.1";
.port = "84";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
}
And the vcl_recv section
import std;
# Respond to incoming requests.
sub vcl_recv {
if (req.method == "BAN") {
# Same ACL check as above:
if (!client.ip ~ purge) {
return(synth(403, "Not allowed."));
}
ban("req.http.host == " + req.http.host +
" && req.url == " + req.url);
# Throw a synthetic page so the
# request won't go to the backend.
return(synth(200, "Ban added"));
} else if (req.method == "PURGE") {
if (!client.ip ~ purge) {
return(synth(405,"Not allowed."));
}
return (purge);
} else if (req.method != "GET" && req.method != "POST" && req.method != "DELETE" && req.method != "PUT") {
return( synth(405, "Method not allowed"));
}
if (req.url ~ "^/piwik/piwik.php") {
set req.backend_hint = server1;
return(pass);
} else if (req.url ~ "^/piwik/piwik.js") {
set req.backend_hint = server1;
return(pass);
} else if (req.url ~ "^/piwik" ) {
# error 404 "Not found";
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~"/node/(\d+)/(.+)$") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~"/monitoring") {
# return( synth(404, "File not found"));
# set req.url = "/404-page-not-found";
return(pass);
} else if (req.url ~"^/user") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "^/admin") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "^/team") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "^/administer") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "/edit?$") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "/add?$") {
# return( synth(404, "File not found"));
set req.url = "/404-page-not-found";
} else if (req.url ~ "^(www\.)?server2.com$") {
set req.backend_hint = server2;
} else if (req.url ~ "^(www\.)?server1.com$") {
set req.backend_hint = server1.com;
}
If I add the following statement to the bottom of the vcl_recv section then I can access server2's backend:
else {
set req.backend_hint = server2;
}
In your VLC you use
req.url ~ "^(www\.)?server2.com$"
but req.url does not contain the host name. What you want to do is probably
req.http.host ~ "^(www\.)?server2\.com$"
or maybe
req.http.host ~ "^(www\.)?server2\.com$" && req.url ~ "^/$"
Related
I am trying to write a code for creating school website.I can control the passwords in terms of matching but I wanna send them to the true page when passwords match and for example I wanna send data which is coming from json and display the html page but no matter how hard I tried,I couldn't.If somebody help me I would be appreciate it.
EDIT:If anybody at least know how can I display the html page after maching the password I would be appreciate it.I wrote a code for that but it did not work.I am gonna show that part in the code.
Here is the code:
var http = require('http'),
url = require('url');
var users = [
{ "username":"admn", "password": "admn", "role": "admin" },
{ "username":"teachr", "password": "teachr", "role": "teacher" },
{ "username":"studnt", "password": "studnt", "role": "student" }
]
var data = [
{ "Projectname":"sdfsf", "projectteacher": "sdfsd", "thestudentthatgottheproject": "tsdf" },
{ "Projectname":"sdfsf", "projectteacher": "sdfsd", "thestudentthatgottheproject": "tsdf" },
{ "Projectname":"sdfsf", "projectteacher": "sdfsd", "thestudentthatgottheproject": "tsdf" }
]
function handle_incoming_request(req, res) {
console.log("INCOMING REQUEST: " + req.method + " " + req.url);
req.parsed_url = url.parse(req.url, true);
var core_url = req.parsed_url.pathname;
if (core_url == '/anasayfa.html') {
res.writeHead(200, { "Content-Type" : "text/html" });
res.end('<!DOCTYPE html><html><head><title>mainpage</title></head><body><form action="http://localhost:8080/ucheck.html" method="get"><input type="text" name="username"><input type="password" name="password"><input type="submit" value="sdfs"></form></body></html>');
}
else if (core_url == '/ur_check.html') {
var getp = req.parsed_url.query;
console.log(getp.username + " " + getp.password);
for(i=0; i<users.length; i++) {
if( (users[i].username == getp.username) && (users[i].password == getp.password)){
switch ( users[i].role ){
case "admin" : //These parts are not working.
function req(request,response)
{
response.writeHead(200, { "Content-Type" : "text/html" });
fs.readFile('./admin.html',null,function(error,data){
if(error)
{
response.writeHead(404);
response.write('File not found.')
}
else{
response.write(data);
}
});response.end();
};break;
case "student" :
function req(request,response)
{
response.writeHead(200, { "Content-Type" : "text/html" });
fs.readFile('./student.html',null,function(error,data){
if(error)
{
response.writeHead(404);
response.write('File not found.')
}
else{
response.write(data);
}
});response.end();
}; break;
case "teacher" :
function req(request,response)
{
response.writeHead(200, { "Content-Type" : "text/html" });
fs.readFile('./teacher.html',null,function(error,data){
if(error)
{
response.writeHead(404);
response.write('File not found.')
}
else{
response.write(data);
}
});response.end();
}; break;
}
res.writeHead(200, { "Content-Type" : "application/json" });
res.end(JSON.stringify( { result: "FOUND", username: users[i].username, password: users[i].password, role: users[i].role }) + "\n");
return;
}
}
res.writeHead(404, { "Content-Type" : "application/json" });
res.end(JSON.stringify({ result: "NOT FOUND", message: "USERNAME OR PASSWORD INVALID" }) + "\n");
}
else {
res.writeHead(404, { "Content-Type" : "application/json" });
res.end(JSON.stringify({ error: "NOT SUPPORTED YET", message: "REQUESTED PAGE DOES NOT EXIST" }) + "\n");
}
var s = http.createServer(handle_incoming_request);
s.listen(8080);
your problem requires a backend. If you know javascript I would suggest you to use express js.
im validating the route /users using router, with render:
<Router>
<Switch>
<Route path = "/" exact component = {Home}></Route>
<Route path = "/login" component = {Login}></Route>
<Route path = "/users" render = {verify_session}></Route>
<Route component = {Not_found}></Route>
</Switch>
</Router>
so each time accesing to /users it will run the function verify_session, this one:
function verify_session() {
axios.get("api/cook/login/verify_session").then((response) => {
if (response.data === 404) {
return <Redirect to = "/login"></Redirect>
}else {
return <Users></Users>
}
});
}
this is in the backend:
router.get("/verify_session", (request, response) => {
if (request.session.user != undefined) {
response.json(200);
}else {
response.json(404);
}
})
it works because when i enter to /users without loggin i can see 404, but it isnt returning the component, if its using a simple validation:
function verify_session() {
let i = 1;
if (i >= 1) {
return <Redirect to = "/login"></Redirect>
}else {
return <Users></Users>
}
}
this way works, but with request get doesnt return anything
This function won't render anything because it doesn't actually return anything. It makes an asynchronous call to an API and those return statements return stuff to the axios' then function instead of the verify_session function.
function verify_session() {
axios.get("api/cook/login/verify_session").then((response) => {
if (response.data === 404) {
return <Redirect to = "/login"></Redirect>
}else {
return <Users></Users>
}
});
}
This function works because, well, it returns a component right away:
function verify_session() {
let i = 1;
if (i >= 1) {
return <Redirect to = "/login"></Redirect>
}else {
return <Users></Users>
}
}
Here is how you will need to change your verify_session function for it work with an API call:
function verify_session() {
const [verified, setVerified] = React.useState(null);
React.useEffect(() => {
axios.get("api/cook/login/verify_session").then((response) => {
if (response.data === 404) {
setVerified(false);
}else {
setVerified(true);
}
});
}, []);
return (
<>
{verified === null ? (
<div>Verifying...</div>
) : verified ? (
<Users></Users>
) : (
<Redirect to = "/login"></Redirect>
)}
</>
);
}
And then use it like so: <Route path = "/users" render = {verify_session}></Route>
Here you create a state inside the verify function that gets updated based on what you get from the API and then render what it needs to render only after the API call is complete.
As a newbie i am handsfree on MERN CRUD application from different tutorials examples.
I am getting error during "npm run dev".
Attempted import error: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker').
Any help would be very helpful.
//registerServiceWorker.js
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service'
);
});
} else {
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log('New content is available; please refresh.');
} else {
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
fetch(swUrl)
.then(response => {
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
Invalid shipping method in magento 1.8.1?
When my cart value in 950 - 999 INR but below 950 or above 999 working fine?
One page controller code is below.
Kindly help me
onePageController.php
<?php
require_once Mage::getModuleDir('controllers', 'Mage_Checkout').DS.'OnepageController.php';
class Webly_QuickCheckout_OnepageController extends Mage_Checkout_OnepageController
{
public function saveBillingAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
// $postData = $this->getRequest()->getPost('billing', array());
// $data = $this->_filterPostData($postData);
$data = $this->getRequest()->getPost('billing', array());
$customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
if (isset($data['email'])) {
$data['email'] = trim($data['email']);
}
$data['use_for_shipping'] = 1;
$result = $this->getOnepage()->saveBilling($data, $customerAddressId);
if (!isset($result['error'])) {
if (!isset($result['error'])) {
if ($this->getOnepage()->getQuote()->isVirtual()) {
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
} elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
$quote =$this->getOnepage()->getQuote();
$quote->getBaseGrandTotal();
$result = $this->getOnepage()->saveShipping($data, $customerAddressId);
if ($quote->getBaseGrandTotal() < 1000) {
$method = 'inchoo_shipping_fixed';
} else {
$method = 'inchoo_shipping_free';
}
// $method = 'flatrate_flatrate';
$result = $this->getOnepage()->saveShippingMethod($method);
Mage::getSingleton('checkout/type_onepage')->getQuote()->getShippingAddress()-> setShippingMethod($method)->save();
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
$result['goto_section'] = 'payment';
} else {
$result['goto_section'] = 'shipping';
}
}
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
}
Can anyone help me in the implementation of nested set behavior https://github.com/creocoder/yii2-nested-sets with Yii2 Menu Widget?
Basically I want the hierarchical sidebar navigation menu like this http://www.surtex-instruments.co.uk/surgical/general-surgical-instruments
Thanks.
In your Model class define this functions:
public static function getTree($selected, $search)
{
$categories = Categories::find()->orderBy('lft')->asArray()->all();
$tree = [];
$index = 0;
foreach ($categories as $category) {
if ($category['parent_category_id'] === NULL) {
$tree[$index]['text'] = $category['category_' . Yii::$app->language];
if ($search) {
$tree[$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'search' => $search, 'string' => $category['category_' . Yii::$app->language]]);
} else {
$tree[$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'string' => $category['category_' . Yii::$app->language] ]);
}
$tree[$index]['id'] = $category['category_id'];
if ($selected) {
if ($selected['category_id'] == $category['category_id']) {
$tree[$index]['state']['selected'] = true;
}
if ($selected['lft'] >= $category['lft'] && $selected['rgt'] <= $category['rgt']) {
$tree[$index]['state']['expanded'] = true;
}
}
if ($category['lft'] + 1 != $category['rgt']) {
Categories::getNodes($tree[$index], $categories, $selected, $search);
}
$index++;
}
}
return $tree;
}
private static function getNodes(&$tree, $categories, $selected, $search)
{
$index = 0;
foreach ($categories as $category) {
if ($tree['id'] == $category['parent_category_id']) {
$tree['nodes'][$index]['text'] = $category['category_' . Yii::$app->language];
if ($search) {
$tree['nodes'][$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'search' => $search, 'string' => $category['category_' . Yii::$app->language]]);
} else {
$tree['nodes'][$index]['href'] = Url::to(['products', 'category' => $category['category_id'], 'string' => $category['category_' . Yii::$app->language]]);
}
$tree['nodes'][$index]['id'] = $category['category_id'];
if ($selected) {
if ($selected['category_id'] == $category['category_id']) {
$tree['nodes'][$index]['state']['selected'] = true;
}
if ($selected['lft'] >= $category['lft'] && $selected['rgt'] <= $category['rgt']) {
$tree['nodes'][$index]['state']['expanded'] = true;
}
}
if ($category['lft'] + 1 != $category['rgt']) {
Categories::getNodes($tree['nodes'][$index], $categories, $selected, $search);
}
$index++;
}
}
}
and use this extension execut/yii2-widget-bootstraptreeview
In the controller file get the menu like this:
public function actionProducts($category = false)
{
...
$data = Categories::getTree($category,'');
In your view file
<?php
...
use execut\widget\TreeView;
...
$onSelect = new JsExpression(<<<JS
function (undefined, item) {
window.location.href = item.href;
}
JS
);
?>
<?= TreeView::widget([
'data' => $data,
'template' => TreeView::TEMPLATE_SIMPLE,
'clientOptions' => [
'onNodeSelected' => $onSelect,
'onhoverColor' => "#fff",
'enableLinks' => true,
'borderColor' => '#fff',
'collapseIcon' => 'fa fa-angle-down',
'expandIcon' => 'fa fa-angle-right',
'levels' => 1,
'selectedBackColor' => '#fff',
'selectedColor' => '#2eaadc',
],
]); ?>