how to fix nginx php-fpm 404 error

Ok, you installed nginx and php-fpm, and happily to open your browser and entered the url, waiting for the page to load, suddenly you saw this nginx 404 error.

So you went to check your nginx configure file and made sure the webroot is correct and file permission is correct, which means they’re readable by nginx and php-fpm user.

You thought you fix the error and went back to the browser and try again, still, the 404 error.

Then you went to google and found a lot of threads from stackoverflow and serverfault, everybody is talking about file/folder permission as that’s really what 404’s root cause.

It took me quite some time to figure out the real reason for my situation. I launched a droplet from digital ocean with latest centos 7 and encountered this error.

The real cause is actually the linux is by default have linux security featured on, you have to disable it
After I ran this command, then everything is ok
setenforce 0

Hope this will help somebody later on.

Amazon Marketplace Web Service mws XML format

Integrating with Amazon’s MWS for XML integration can be a pain, especially since the small amount of documentation written on the subject is often contradictory and unclear. This guide should help point you in the right direction. To be clear, this guide will only focus its attention to the xml file itself. That is, this guide will explain what each tag means and what best to include in each tag for SEO/ranking higher on amazon. This guide will NOT cover: How to implement these notes. You or your team must already have a programmer to implement the XML file. This guide is about how best to utilize the tags provided in the schema.

HOW TO USE THE GUIDE

  • All text in bold is a tag; subtags are marked by a bullet point. Tag descriptions and specifications are not bolded.
  • To completely add a product via XML, you’ll need to upload four different XML files: Product.xml, productimage.xml, inventory.xml and price.xml. This guide is sorted into these four files.
  • This guide was written with area rugs as an example product, so some tags might not apply to your product.
  • Be sure to complete as many tags and possible and be sure to follow these guidelines as closely as possible to ensure that your product ranks as high as possible.
  • Each item must be sent as a new message in the messageID tag. This is present in each of the xml files however message ID’s do not need to match to add information about the same product.

Sample Product XML

The two links below contain sample xml files:

Product XML Tag Guide and Reference

Sample of completed product.xml (see below for information about each tag)

<?xml version=”1.0″?> <AmazonEnvelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”amzn-envelope.xsd”> <Header> <DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>ATVPDKIKX0DER</MerchantIdentifier> </Header> <MessageType>Product</MessageType><PurgeAndReplace>false</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <Product> <SKU>220</SKU> <StandardProductID> <Type>UPC</Type> <Value>680242554716</Value> </StandardProductID> <ProductTaxCode>A_GEN_TAX</ProductTaxCode> <LaunchDate>2014-04-22T04:00:00</LaunchDate> <Condition> <ConditionType>New</ConditionType> </Condition> <DescriptionData> <Title>eCarpetGallery Hand woven Chobi Sumak 5-Feet 6-Inch by 8-Feet 6-Inch Wool Sumak, Aqua 2, Beige, Copper, Cream</Title><Brand>eCarpetGallery</Brand> <Description>These luxurious flat-woven rugs are handmade by Afghan master weavers. They are woven using locally handspun wool and the beautiful variety of colors and hues is achieved by using vegetable and mineral dyes. These stately rugs are perfect for traditional, classical and modern decors.</Description><BulletPoint>Luxurious flat-woven and no pile rugs, handmade by Afghan master weavers (ECG220)</BulletPoint> <BulletPoint>Transitional style sumak</BulletPoint> <BulletPoint>Imported from Pakistan</BulletPoint> <BulletPoint> Flat-weave and constructed from 100% Wool with 100% Cotton foundation</BulletPoint> <BulletPoint>5-Feet 6-Inch by 8-Feet 6-Inch (167cm x 259cm)</BulletPoint><ItemDimensions> <Length unitOfMeasure=”CM”>259</Length> <Width unitOfMeasure=”CM”>167</Width> <Height unitOfMeasure=”CM”>0</Height> <Weight unitOfMeasure=”LB”>27.9</Weight> </ItemDimensions> <PackageDimensions> <Length unitOfMeasure=”CM”>259</Length> <Width unitOfMeasure=”CM”>167</Width> <Height unitOfMeasure=”CM”>0</Height> </PackageDimensions> <PackageWeight unitOfMeasure=”LB”>27.9</PackageWeight> <ShippingWeight unitOfMeasure=”LB”>27.9</ShippingWeight> <MSRP currency=”CAD”>941.90</MSRP><Manufacturer>eCarpetGallery</Manufacturer><MfrPartNumber>220</MfrPartNumber><SearchTerms>arpet;bedrooms;carpet;carpets;carpt;cheap;crpet</SearchTerms><SearchTerms>decor;expensive;flat;flatweave;home;kids;kitchen</SearchTerms> <SearchTerms>less;living;luxury;new;pakistan;pakistani;panel</SearchTerms><SearchTerms>quality;rectangle;rectangular;rgs;room;rug;rugs</SearchTerms><SearchTerms>sale;transitional;vintage;weave</SearchTerms><UsedFor>bedroom</UsedFor> <UsedFor>living room</UsedFor> <UsedFor>dining room</UsedFor> <UsedFor>floor</UsedFor> <UsedFor>decor</UsedFor> <ItemType>handmade-rugs</ItemType><OtherItemAttributes>Rectangular</OtherItemAttributes><OtherItemAttributes>Panel</OtherItemAttributes><OtherItemAttributes>Transitional</OtherItemAttributes><OtherItemAttributes>Artisan</OtherItemAttributes><OtherItemAttributes>Urban</OtherItemAttributes><TargetAudience>Adults</TargetAudience><TargetAudience>Children</TargetAudience><TargetAudience>Men</TargetAudience><TargetAudience>Women</TargetAudience><RecommendedBrowseNode>6647000011</RecommendedBrowseNode><RecommendedBrowseNode>6647007011</RecommendedBrowseNode></DescriptionData> <ProductData> <Home> <ProductType> <FurnitureAndDecor> <ColorMap>Green</ColorMap> <Material>Wool & Wool Blend</Material> <!–<MaximumCoverageArea unitOfMeasure=”square-cm”>18581</MaximumCoverageArea>–> <Shape>Rectangular</Shape> <VariationData> <Size>6′ x 9′</Size> <Color>Green</Color> <StyleName>Contemporary</StyleName> </VariationData> </FurnitureAndDecor> </ProductType> <!–<VariationData> <VariationTheme> <Size>5 x 8</Size> </VariationTheme> </VariationData>–> <CountryAsLabeled>PK</CountryAsLabeled><CountryOfOrigin>PK</CountryOfOrigin><CountryProducedIn>Pakistan</CountryProducedIn><ImportDesignation>Imported</ImportDesignation> <FabricType>100% Wool</FabricType><PatternName>Geometric</PatternName> <DisplayLength unitOfMeasure=”CM”>259</DisplayLength> <DisplayWidth unitOfMeasure=”CM”>167</DisplayWidth> <DisplayWeight unitOfMeasure=”LB”>27.9</DisplayWeight> <ManufacturerWarrantyDescription>30-day Money Back Guarantee </ManufacturerWarrantyDescription> </Home> </ProductData> </Product> </Message> </AmazonEnvelope>

Tag Information

Remember! Each tag is in bold, sabotages are the bolded and bulleted text. Explanations is the normal weight text.

SKU

  • Our SKU

Standard ProductID

  • Type
    • ASIN preferred; UPC if not available
  • Value
    • The value

ProductTaxCode

  • A_GEN_TAX

LaunchDate

  • The on which date feed is generated

DiscontinueDate

  • Ignore

ReleaseDate

  • The date product is to be released. 99% of the time this will be the launch date.

ExternalProductURL

  • Ignore

OffAmazonChannel

  • Ignore

OnAmazonChannel

  • Ignore

Condition

  • ConditionType
    • Must be one of the following: New, UsedLikeNew, UsedVeryGood, Refurbished
  • ConditionNote (Only if condition type is not new)
    • Note about condition – Max 2000 chars

Rebate

  • This can be left empty unless we plan on offering rebates

ItemPackageQuantity

  • Ignore: Our delivered packages are only one package

Number of Items

  • Ignore: When someone orders a rug, it is the only item that is sent

LiquidVolume

  • Ignore

DescriptionData

  • Title
    • If material is NOT synthetic
      • [Company name] + [Collection] +[Width] + [Unit of Measure Spelled out] +[Length] + [Unit of Measure Spelled out] + [Material] + [Rug Type] + “,” + Colour
        • For example: eCarpetGallery Prestige 5’5” x 7’8” Wool Rug, Red
    • If material IS synthetic
      • [Company name] + [Collection] +[Width] + [Unit of Measure Spelled out] +[Length] + [Unit of Measure Spelled out] + [Rug Type] + “,” + Colour
        • For example: eCarpetGallery Prestige 5’5” x 7’8” Rug, Red
  • Brand
  • [Company name]
  • Designer
  • Not sure if ignore or not
  • Description
  • Our romance statement – Max 2000 chars
  • BulletPoint (1)
  • Small description
  • BulletPoint (2)
  • [Style] + “style” + [Construction Type] + “made” + [Rug Type]
  • BulletPoint (3)
  • If not made in CA or USA
    • Imported from + [Country of Origin]
  • If made in CA or USA
    • Proudly(?) Made in + [Country of Origin]
  • BulletPoint (4)
  • [Material]
  • BulletPoint (5)
  • If uploading to US
    • [Size] + “Feet”
  • if Canada
    • [Size] + “Feet ([SizeMeters] + “Meters)”
  • ItemDimensions (each of the following can be excluded safely)
  • Length (with name=unitOfMeasure [CM,M,IN,FT])
    • Value
  • Width (with name=unitOfMeasure [CM,M,IN,FT])
    • Value
  • Height (with name=unitOfMeasure [CM,M,IN,FT])
  • Value
  • Weight (with name=unitOfMeasure [LB,KG])
  • Value
  • PackageDimensions
  • Length (with name=unitOfMeasure [CM,M,IN,FT])
    • Value
  • Width (with name=unitOfMeasure [CM,M,IN,FT])
    • Value
  • Height (with name=unitOfMeasure [CM,M,IN,FT])
    • Value
  • PackageWeight (with name=unitOfMeasure [LB,KG])
  • ShippingWeight (with name=unitOfMeasure [LB,KG])
  • MerchantCatalogNumber
    • For pro merchants only
  • MSRP (with name=currency [USD,CAD])
    • Value
  • MSRPWithTax (with name=currency [USD,CAD])
    • Value
  • MaxOrderQuantity
    • Positive integer
  • SerialNumberRequired
    • True/False
  • Prop65
    • Ignore since we are not located in California
  • CPSIAWarning
    • no_warning_applicable
  • CPSIAWarningDescription
    • Ignore
  • LegalDisclaimer
    • Ignore
  • Manufacturer
    • [Company name]
  • MfrPartNumber
    • The SKU
  • SearchTerms (1)
    • Comma delimited max 50 chars
  • SearchTerms (2)
    • Comma delimited max 50 chars
  • SearchTerms (3)
    • Comma delimited max 50 chars
  • SearchTerms (4)
    • Comma delimited max 50 chars
  • SearchTerms (5)
    • Comma delimited max 50 chars
  • PlatinumKeywords
    • Ignore
  • Memorabilia
    • False
  • Autographed
    • False
  • UsedFor (1)
    • dining room
  • UsedFor (2)
    • living room
  • UsedFor (3)
    • decor
  • UsedFor (4)
    • floor
  • UsedFor (5)
    • bedroom
  • ItemType
    • area-rugs
    • braided-rugs
    • hand-knotted-rugs
    • handmade-rugs
    • hand-tufted-rugs
    • machine-made-rugs
    • runners
  • OtherItemAttributes (Can only be one of the follows terms)
    • Casual, Chic, Contemporary, Decorative, Rectangular, Art Deco, Asian Influence, Casual, Checkered, Colonial, Contemporary, Country, Rustic, Decorative, Floral French, French Country, Garden, Handmade Rugs, Lodge, Natural Fiber Rugs, Nonskid, Nonstandard, Shape, Novelty, Oval, Patchwork Patterns, Print, Rectangular, Round, Santa Fe, Shabby, Chic, Solid, Square, Striped, Traditional, Victorian
  • OtherItemAttributes (Can only be one of the follows terms)
    • Casual, Chic, Contemporary, Decorative, Rectangular, Art Deco, Asian Influence, Casual, Checkered, Colonial, Contemporary, Country, Rustic, Decorative, Floral French, French Country, Garden, Handmade Rugs, Lodge, Natural Fiber Rugs, Nonskid, Nonstandard, Shape, Novelty, Oval, Patchwork Patterns, Print, Rectangular, Round, Santa Fe, Shabby, Chic, Solid, Square, Striped, Traditional, Victorian
  • OtherItemAttributes (Can only be one of the follows terms)
    • Casual, Chic, Contemporary, Decorative, Rectangular, Art Deco, Asian Influence, Casual, Checkered, Colonial, Contemporary, Country, Rustic, Decorative, Floral French, French Country, Garden, Handmade Rugs, Lodge, Natural Fiber Rugs, Nonskid, Nonstandard, Shape, Novelty, Oval, Patchwork Patterns, Print, Rectangular, Round, Santa Fe, Shabby, Chic, Solid, Square, Striped, Traditional, Victorian
  • OtherItemAttributes (Can only be one of the follows terms)
    • Casual, Chic, Contemporary, Decorative, Rectangular, Art Deco, Asian Influence, Casual, Checkered, Colonial, Contemporary, Country, Rustic, Decorative, Floral French, French Country, Garden, Handmade Rugs, Lodge, Natural Fiber Rugs, Nonskid, Nonstandard, Shape, Novelty, Oval, Patchwork Patterns, Print, Rectangular, Round, Santa Fe, Shabby, Chic, Solid, Square, Striped, Traditional, Victorian
  • OtherItemAttributes (Can only be one of the follows terms)
    • Casual, Chic, Contemporary, Decorative, Rectangular, Art Deco, Asian Influence, Casual, Checkered, Colonial, Contemporary, Country, Rustic, Decorative, Floral French, French Country, Garden, Handmade Rugs, Lodge, Natural Fiber Rugs, Nonskid, Nonstandard, Shape, Novelty, Oval, Patchwork Patterns, Print, Rectangular, Round, Santa Fe, Shabby, Chic, Solid, Square, Striped, Traditional, Victorian
  • TargetAudience
    • Adults
  • TargetAudience
    • Children
  • TargetAudience
    • Men
  • TargetAudience
    • Women
  • SubjectContent
    • Ignore
  • IsGiftWrapAvailable
    • I feel like we should put this as True since it will fill up some white space on our listing
  • IsGiftMessageAvailable
    • Boolean
  • PromotionKeywords
    • Haven’t found any information on this, probably for special amazon members
  • IsDiscontinuedByManufacturer
    • Ignore
  • DeliveryScheduleGroupID
    • Ignore
  • DeliveryChannel
    • Ignore
  • PurchasingChannel
    • Ignore
  • MaxAggregateShipQuantity
    • Ignore (Max amount of these items which may be shipped at the same time)
  • IsCustomizable
    • False
  • CustomizableTemplateName
    • Ignore
  • RecommendedBrowseNode (1 – CA only)
    • All Area Rugs: 6647000011
    • RecommendedBrowseNode (2 – CA only)
      • Braided: 6647002011
      • Hand-knotted: 6647005011
      • Hand tufted: 6647006011
      • Handmade: 6647007011
      • Handloomed: 6647007011
      • Machinemade: 6647008011
      • Runner: 6647010011
  • FEDAS_ID
    • Ignore
  • TSDAgeWarning
    • Ignore
  • TSDWarning
    • Ignore
  • TSDLanguage
    • Ignore
  • OptionalPaymentTypeExclusion
    • Ignore

END DESCRIPTION DATA TAG

PromoTag

  • PromoTagType
    • Value must be one of the following: Sale, New, NewArrival, WebOnly, Clearance, LimitedOffer, SpecialOffer, SpecialPurchase, OnlyInStores
  • EffectiveFromDate
    • Format: 2002-09-24
  • EffectiveThroughDate
    • Format: 2002-09-24

DiscoveryData

  • Ignore
  • Priority
    • Ignore
  • BrowseExclusion
    • Ignore
  • RecommendationExclusion
    • Ignore

ProductData

  • Home
  • ProductType
  • FurnitureAndDecor
  • ColorMap
  • Color Map must be one of the following: beige, black, blue, brown, Clear, Gold, Green, Grey (correct spelling for both CA and USA), Ivory, Multi, Orange, Pink, Purple, Red, Silver, White, Yellow
  • IsStainResistant
    • Boolean
  • Material
    • Aluminum, Bamboo, Bamboo-derived rayon, Beech, Birch, Brass, Bronze, Cashmere, Cast Iron, Cedar, Chenille, Cherry, Chrome, Copper, Cotton, Denim, Down & Feather-Fill, Elm, Fabric, Flannel, Fleece, Glass, Hardwood, Jersey, Leather & Suede, Leather, Mahogany, Maple, Marble, Memory foam, Metal, Microfiber, Nickel, Oak, Other, Paper, Paraffin, Percale, Pewter, Pine, Plastic, Polycast, Polyester & Polyester Blend, Polyresin, Polyurethane, Porcelain, Rattan, Rattan & Wicker, Recycled Material, Rosewood, Resin, Sateen, Satin, Silk, Silver, Stainless Steel, Steel, Stone, Straw, Suede, Synthetic, Teak, Terrycloth, Tin, Velvet, Vinyl, Wax, Wicker, Walnut, Willow, Wood, Wool & Wool Blend, Wrought and Cast Iron,
    • Max 50 chars – Must be one of the following: Acrylic, Acrylic Linen, Denim, Denim & Chambray, Down & Feather-Fill, Felt, Faux Fur, Fleece, Flannel, Hemp, Leather, Leather & Suede, Linen, Natural, Multi-Ply, Microfiber, Nylon, Polyester, Polyester & Polyester Blend, Polyurethane, Recycled Material, Recylced, Silk, Synthetic, Wool, Velvet, Wool & Wool Blend
  • MaximumCoverageArea (name = unitOfMeasure [square-ft, square-in, square-cm)
    • Value
  • Shape
    • Oval, Rectangular, Round or Square
  • VariationData
  • Size
    • 2’x3’,
    • 2.5’ x 9’,
    • 2.5’ x 13’,
    • 3’ x 5’,
    • 4’ x 6’,
    • 5’ x 8’,
    • 6’ x 9’,
    • 8’ x 10’,
    • 9’ x 12’,
    • Round,
    • Square
  • Color
    • Color spelt out (string)
  • StyleName
    • Must be one of the following: Antique, Art Deco, Asian, Baroque, Cape Cod, Casual, Chinese, Colonial, Contemporary, Cottage, Country Rustic, Eclectic, English, French, French Country, Garden, Italianate, Japanese, Latin, Lodge, Mediterranean, Mission, Modern, Moroccan, Old World, Scandanavian, Shabby Chic, Shaker, Southwestern, Traditional, Tropical, Victorian
  • CountryAsLabeled
    • Must be 2 char country code
  • CountryOfOrigin
    • Must be 2 char country code
  • CountryProducedIn
    • Full country name
  • ImportDesignation
    • If posting from CA account and country of origin is not Canada then put “Imported”, else “Made in Canada
    • If posting from USA account and country of origin is not USA then put “Imported”, else “Made in USA”
  • FabricType
    • 100 chars long, each fabric separated by a “/” and numerated with a % amount
  • PatternName
    • Must be one of the following: Floral, Solid, Striped, Print, Geometric, Patchwork, Paisley, Bordered, Plaid, Checkered, Polka Dot, Gingham, Moire
  • DisplayLength (name = unitOfMeasure [FT])
    • Must be in feet
  • DisplayWidth (name = unitOfMeasure [FT])
    • Must be in feet
  • DisplayWeight (name = unitOfMeasure [LB])
    • Must be in pounds
  • ManufacturerWarrantyDescription
    • 30-day Money Back Guarantee

Inventory XML

Sample inventory.xml

<?xml version=”1.0″ encoding=”utf-8″ ?> <AmazonEnvelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”; xsi:noNamespaceSchemaLocation=”amzn-envelope.xsd”><Header> <DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>M_SELLER_354577</MerchantIdentifier> </Header> <MessageType>Inventory</MessageType> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <Inventory> <SKU>ASUSVNA1</SKU> <Quantity>8</Quantity> <FulfillmentLatency>1</FulfillmentLatency> </Inventory> </Message> <Message> <MessageID>2</MessageID> <OperationType>Update</OperationType> <Inventory> <SKU>ASUS8VM</SKU> <Quantity>6</Quantity> <FulfillmentLatency>1</FulfillmentLatency> </Inventory> </Message> </AmazonEnvelope>

Inventory XML Dictionary

Inventory

  • SKU
    • SKU
  • Quantity
    • Quantity
  • FulfillmentLatency
  • Amount of days it takes from receiving order to shipping

Price XML

<?xml version=”1.0″ encoding=”utf-8″ ?> <AmazonEnvelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”; xsi:noNamespaceSchemaLocation=”amzn-envelope.xsd”><Header> <DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>M_SELLER_354577</MerchantIdentifier> </Header> <MessageType>Price</MessageType> <Message> <MessageID>1</MessageID> <Price> <SKU>ASUSVNA1</SKU> <StandardPrice currency=”USD”>10.99</StandardPrice> </Price> </Message> <Message> <MessageID>2</MessageID> <Price> <SKU>ASUSVNA1669</SKU> <StandardPrice currency=”USD”>204.99</StandardPrice> <Sale> <StartDate>2008-10-01T00:00:00Z</StartDate> <EndDate>2009-01-31T00:00:00Z</EndDate> <SalePrice currency=”USD”>28.38</SalePrice> </Sale> </Price> </Message> </AmazonEnvelope>

Price XML Dictionary

Price

  • SKU
    • SKU
  • StandardPrice (name=currency [CAD,USD])
    • Price rug will be sold at
  • Sale
  • StartDate
    • Date long format
  • EndDate
    • Date long format
  • SalePrice (name=currency [CAD,USD])
    • Sale price

ProductImage XML

<?xml version=”1.0″ encoding=”utf-8″ ?> <AmazonEnvelope xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”; xsi:noNamespaceSchemaLocation=”amzn-envelope.xsd”><Header> <DocumentVersion>1.01</DocumentVersion><MerchantIdentifier>M_SELLER_354577</MerchantIdentifier> </Header> <MessageType>ProductImage</MessageType> <Message> <MessageID>1</MessageID> <OperationType>Update</OperationType> <ProductImage> <SKU>ASUSVNA1</SKU> <ImageType>Main</ImageType><ImageLocation>http://www.abc.com/images/ASUSVNA1.gif</ImageLocation&gt; </ProductImage> </Message> <Message> <MessageID>2</MessageID> <OperationType>Update</OperationType> <ProductImage> <SKU>ASUSVNA1987/4G</SKU> <ImageType>Main</ImageType> <ImageLocation>http://www.abc.com/images/ASUSVNA1987.jpg</ImageLocation&gt; </ProductImage> </Message> </AmazonEnvelope>

Price XML Dictionary

ProductImage

  • SKU
  • SKU
  • ImageType (one of the following)
    • Main: Main image
    • Swatch: different colour variations (will be rescaled to 30×30 pixels)
    • Alternate (PT1-8): Secondary photos to be displayed alongside others
  • ImageLocation
    • URL where image is located

Image Requirements

Format – photographs, not drawings

Color Model – RGB (no CMYK images)

Background – white or clear, no borders or words, no brand logos

Recommended dimensions – Images should be 1000 pixels or larger in either height or width as this will

enable zoom functionality on the website (zoom has proven to enhance sales). The smallest your file should

be is 500 pixels on the longest side. Consistently sized images are strongly recommended.

File type – JPEG (.jpg) or GIF (.gif)

Resolution – 72 pixels per inch

Animation – none

create local frontend development envoirment

1)  Download nodejs and install https://nodejs.org/en/, on Mac, it will install Node.js and npm to /usr/local

screen-shot-2016-09-09-at-12-26-25-pm

2) install gulp

https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md

screen-shot-2016-09-09-at-12-29-29-pm

3) install bower

https://bower.io/

screen-shot-2016-09-09-at-12-32-54-pm

 

how to prevent iframe from accessing parent frame

iframe sandbox attribute is really great to lock down the permissions

Given an iframe with an empty sandbox attribute (<iframe sandbox src="..."> </iframe>), the framed document will be fully sandboxed, subjecting it to the following restrictions:

  • JavaScript will not execute in the framed document. This not only includes JavaScript explicitly loaded via script tags, but also inline event handlers and javascript: URLs. This also means that content contained in noscript tags will be displayed, exactly as though the user had disabled script herself.
  • The framed document is loaded into a unique origin, which means that all same-origin checks will fail; unique origins match no other origins ever, not even themselves. Among other impacts, this means that the document has no access to data stored in any origin’s cookies or any other storage mechanisms (DOM storage, Indexed DB, etc.).
  • The framed document cannot create new windows or dialogs (via window.open or target="_blank", for instance).
  • Forms cannot be submitted.
  • Plugins will not load.
  • The framed document can only navigate itself, not its top-level parent. Setting window.top.location will throw an exception, and clicking on link with target="_top" will have no effect.
  • Features that trigger automatically (autofocused form elements, autoplaying videos, etc.) are blocked.
  • Pointer lock cannot be obtained.
  • The seamless attribute is ignored on iframes the framed document contains.

This is nicely draconian, and a document loaded into a fully sandboxed iframe poses very little risk indeed. Of course, it also can’t do much of value: you might be able to get away with a full sandbox for some static content, but most of the time you’ll want to loosen things up a bit.

With the exception of plugins, each of these restrictions can be lifted by adding a flag to the sandbox attribute’s value. Sandboxed documents can never run plugins, as plugins are unsandboxed native code, but everything else is fair game:

  • allow-forms allows form submission.
  • allow-popups allows popups (window.open(), showModalDialog(), target=”_blank”, etc.).
  • allow-pointer-lock allows (surprise!) pointer lock.
  • allow-same-origin allows the document to maintain its origin; pages loaded from https://example.com/ will retain access to that origin’s data.
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically (as they’d be trivial to implement via JavaScript).
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window.

One important thing to note is that the sandboxing flags applied to a frame also apply to any windows or frames created in the sandbox. This means that we have to add allow-forms to the frame’s sandbox, even though the form only exists in the window that the frame pops up.

With the sandbox attribute in place, the widget gets only the permissions it requires, and capabilities like plugins, top navigation, and pointer lock remain blocked. We’ve reduced the risk of embedding the widget, with no ill-effects. It’s a win for everyone concerned.

http://www.w3schools.com/tags/att_iframe_sandbox.asp

http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

Javascript: Understanding Objects vs Arrays and When to Use Them

What are Objects and how do they differ from Arrays in Javascript?
When is it advantageous to use one over the other?

I ran into this question several times while browsing through stackoverflow’s javascript queue so I decided to recycle my answers, elaborate a bit and make it into a blog post. If you are new to javascript, understanding these two data types is very important and could potentially save you some headache down the road.

Declaration & Augmentation

Array(s):

var myArray = new Array(); // Array constructor (try to avoid)
// is the equivalent of:
var myArray = []; // Array literal (preferred way)
var anotherArray = [1, 5, “string”, {hello: “world”}] // Array with some elements of mixed type
Arrays come with several, very useful native methods. We can add a new element to existing array instance using push() and remove the last element from the array via pop(). We can also use splice() to remove n elements and/or insert new element(s) at index i.

myArray.push(“this”); // push a string on the stack
myArray.push(“is”, “neat”, “!”); // push multiple comma separated elements, in this case 3 strings.

console.log(myArray); // prints [“this”, “is”, “neat”, “!”]

var a = myArray.pop(); // pops the last element from the stack
console.log(a); // prints “!”
console.log(myArray); // prints [“this”, “is”, “neat”]

// remove n elements starting at index i from myArray, where i = 0 and n = 2 in this case.
// splice(i, n, k0, k1, …, kn) modifies myArray, returns spliced chunk as an array and optionally inserts k0-kn new elements at index i.
var b = myArray.splice(0, 2); // not to be confused with slice()
console.log(b); // prints [“this”, “is”]
console.log(myArray); // prints [“neat”]

// we can also use splice to add new elements at index i
myArray.splice(0, 0 ,”isn’t”, “this”); // remove n = 0 elements and insert “isn’t” and “this” starting at index i = 0
myArray.push(“?”); // push “?” at the end of the stack
console.log(myArray); // prints [“isn’t”, “this”, “neat”, “?”]

// we could have done last two operations in one step by doing the following
myArray = [“this”, “is”, “neat”, “?”];
myArray.splice(0, 2,”isn’t”, “this”);
console.log(myArray); // prints [“isn’t”, “this”, “neat”, “?”]
You can find out more about Arrays, their methods and properties at MDN.

Object(s):

var myObject = new Object(); // Object constructor (try to avoid)
// is the equivalent of:
var myObject = {}; // Object literal (preferred way)
Think about objects as associative arrays, i.e. list of key -> value pairs.
These keys are referred to as object properties.
Follow this pattern when declaring new objects:

// Note: each object property declaration is comma separated.
// You don’t need to prefix each object property like I did in the example below.
// You can use any (read most) valid javascript strings as an object property.
var myObject = {
propertyString: “this is a string”,
propertyAnotherString: “this is another string”,
propertyMixedArray: [“item 1”, “item 2”, 1, 2, {}],
// Note above, we have different data types in the array:
// two strings, two ints/numbers and one empty object.
// This is completely legal in javascript.
propertyObject: { someProperty: “and so on…” }
};
Javascript is a dynamic language. You are allowed to extend/augment objects and their prototype after object has been defined as well as during runtime.

// Adding additional properties is OK too.
// Note: this time we use “=” instead of “:” to assign value
myObject.additionalProperty = “Additional property”;

// prints “this is a string”
console.log(myObject.propertyString);

// also prints “this is a string”
// I’m treating object as an associative array or hashtable
console.log(myObject[“propertyString”]);

// also prints “this is a string”
// we can use variables as well to dynamically access keys.
var keyFromVariable = “propertyString”;
console.log(myObject[keyFromVariable]);

// Couple of other examples.
console.log(myObject.propertyMixedArray[1]); // prints “item 2”
console.log(myObject.propertyObject.someProperty); // prints “and so on…”
console.log(myObject.additionalProperty); // prints “Additional property”
Deleting a property is very simple:

var newObj = {
foo: “here be dragons”,
bar: “foo is a lie”
};
delete newObj.bar; // is the equivalent of delete newObj[‘bar’];
console.log(newObj); // prints Object {foo: “here be dragons”}
Javascript community prefers using literal notation as it makes the code cleaner and easier to understand. Whether you decide to go with literal declaration or using constructors, be consistent. Read more about Objects on MDN.

Checking if Property or Value Exists

Array(s):

Generally when we work with arrays, we care less about indexes and more about values.
One of the common operations we perform with Arrays is checking if a certain value is in the array.
This is easily accomplished using indexOf() method.

var testArr = [1, 4, 3, 0, “sticks”, 3, “foo”];

// Check if there is at least one instance of number 3 in testArr;
var i = testArr.indexOf(3); // value of i will be 2 as that is where the first instance of number 3 is located
var nope = testArr.indexOf(“jetpack”); // value of nope will be -1 since testArr doesn’t contain a string “jetpack”
// Note: testArr.indexOf(value) will return an integer between 0 and (testArr.length-1) if value exists
// or -1 if value is not found in the array.

// This will print ‘Woo hoo!’ since 3 is in testArr;
if (i != -1) {
console.log(‘Woo hoo!’);
} else {
console.log(‘Bummer!’);
}

// Alternatively to checking if ((-1 * i) <= -1) or if (i != -1),
// we could have done (I personally prefer this approach):
if (~i) { // This is (~) tilda, NOT (-) dash/minus
console.log(‘Woo hoo!’);
} else {
console.log(‘Bummer!’);
}
// or
if (~testArr.indexOf(3)) { // This is (~) tilda, NOT (-) dash/minus
console.log(‘Woo hoo!’);
} else {
console.log(‘Bummer!’);
}
To find out more about Bitwise NOT (~) operator and why it works in this scenario, check out the good ole MDN.

Object(s):

In contrast to Arrays, we generally want to know if an Object contains a certain property. Usually we will write a function that takes Object as an argument and will expect that it contains a certain set of properties. This Object can come from an API or some other piece of code and we shouldn’t rely on it having all the properties we expect. It is always a good idea to check whether the property exists before accessing the value behind that property. Objects come with hasOwnProperty() method which allows us to do just that.

var testObj = {
foo: “tball”
};

// prints: ‘We got ourselves a foo!’
if (testObj.hasOwnProperty(‘foo’)) {
console.log(‘We got ourselves a foo!’);
} else {
console.log(‘No foo for you!’);
}

// prints: Too drunk, cannot locate the bar. Football at my place!
if (testObj.hasOwnProperty(‘bar’)) {
console.log(‘We are at the bar, watching the football game’);
} else {
console.log(‘Too drunk, cannot locate the bar. Football at my place!’);
}
Ok folks, I have a confession to make. I was not entirely honest with you. There is a “small” detail that I have purposefully omitted when comparing these two data types. Read Part 2 of this post to find out more!